首页 > 厂商 > 知识 > trylock,我想在写文件的时候将这个文件锁定不让其他线程或者程序操作该

trylock,我想在写文件的时候将这个文件锁定不让其他线程或者程序操作该

来源:整理 时间:2025-03-06 22:16:56 编辑:智能门户 手机版

本文目录一览

1,我想在写文件的时候将这个文件锁定不让其他线程或者程序操作该

两种方式第一种是使用RandomAccessFile,创建RandomAccessFile对象时使用rws参数,如——RandomAccessFile raf = new RandomAccessFile(new File("c:/test.txt"), "rws");即以锁定方式对文件进行写入,就是所谓的独占方式。第二种是使用FileChannel——RandomAccessFile raf = new RandomAccessFile(new File("c:/test.txt"), "rw");FileChannel fc = raf.getChannel();FileLock fl = fc.tryLock();if (fl.isValid()) // 文件锁定成功,写入操作代码省略 fl.release(); // 释放文件锁}这种方式是用FileChannel的tryLock()方法获取文件锁,它还有一个lock()方法也可以获取文件锁,区别是lock()方法是阻塞式的,只有成功获取到文件锁才能进行后续操作,否则一直等待。

我想在写文件的时候将这个文件锁定不让其他线程或者程序操作该

2,JAVA 如何防止同时操作一个文件

服务端用一个Map来记录用户操作的文件。。 当一个用户请求操作file1文件的时候,就用: if(map.push(file,user1)) System.out.println("success"); 根据能否push到map里面,来表示该文件是否正在被使用。。 如果一个用户操作完该文件,调用map.remove(file1)即可
windows 会自动控制。linux系统,你就用同步方法吧,把对文件的操作写到同步方法里面。
我们通过RandomAccessFile这个随机读取流来操作文件速度上面会有一点慢、但不是极其大的文件一般可以忽略。 我们通过FileChannel对象来获得锁 Trylock 与lock方法 tryLock()是非阻塞式的,它设法获取锁,但如果不能获得,例如因为其他一些进程已经持有相同的锁,而且不共享时,它将直接从方法调用返回。 lock()是阻塞式的,它要阻塞进程直到锁可以获得,或调用lock()的线程中断,或调用lock()的通道关闭。 对独占锁和共享锁的支持必须由底层的操作系统提供。锁的类型可以通过FileLock.isShared()进行查询。另外,我们不能获取缓冲器上的锁,只能是通道上的。 File file=new File("D:/test.txt"); //给该文件加锁 RandomAccessFile fis = new RandomAccessFile(file, "rw"); FileChannel fcin=fis.getChannel(); FileLock flin=null; while(true){ try { flin = fcin.tryLock(); break; } catch (Exception e) { System.out.println("有其他线程正在操作该文件,当前线程休眠1000毫秒"); sleep(1000); } }

JAVA 如何防止同时操作一个文件

3,关于ReentrantLock类的trylock的使用问题

public class Main public static void main(String[] args) throws InterruptedException final ReentrantLock lock = new ReentrantLock(); Thread a; for (int index = 0; index < 4; index++) a = new Thread(new ThreadForTryLock3(lock)); a.setName("Thread" + index); a.start(); } }}class ThreadForTryLock3 implements Runnable private ReentrantLock lock; public ThreadForTryLock3(ReentrantLock lock) this.lock = lock; } public void run() System.out.println("Pre: lock state is: " + lock + ".\n\tThreadName is: " + Thread.currentThread().getName()); boolean isLock = lock.tryLock(); if(isLock) System.out.println("lock.tryLock(): " + isLock + ".\n\tThreadName is: " + Thread.currentThread().getName()); try Thread.sleep(100); System.out.println("sleep end" + ".\n\tThreadName is:" + Thread.currentThread().getName()); } catch (InterruptedException e) e.printStackTrace(); } finally System.out.println("Post: lock state is" + lock.toString() + ".\n\tThreadName is: " + Thread.currentThread().getName()); if (lock.isLocked()) lock.unlock(); System.out.println(lock.isLocked()); } } }}你的代码有些问题,tryLock必须注意:如果这个方法返回false,则程序不能继续执行临界区代码。如果执行了,这个程序很可能会出现错误的结果。你的代码中就是不论是否拿到lock 都会执行临界区。

关于ReentrantLock类的trylock的使用问题

4,java 线程怎么实现定时中断

1、从JAVA5.0开始,提供了新的选择:ReentrantLock。2、可定时和可轮询的锁获取模式由tryLock方法实现。3、使用tryLock试图获得的锁如果不能同时获得,就回退,并重新尝试。休眠时间由一个特定组件管理。(下面的代码完成转帐)public boolean transferMoney(Account fromAcct,AccounttoAcct,DollarAmonunt amount,long timeout,TimeUnit unit) throwsInsufficientFundsException,InterruptedException longfixedDelay=getFixedDelayComponentNanos(timeout,unit); longrandMod=getRandomDelayModulusNanos(timeout,unit); longstopTime=System.nanoTime()+unit.toNanos(timeout);while (true) if (fromAcct.lock.tryLock()) try if(toAcct.lock.tryLock()) try if (fromAcct.getBalance().compareTo(amount)<0) thrownew InsufficientFundsException(); else fromAcct.debit(amount); toAcct.credit(amount); returntrue; } }finally } }finally } } if(System.nanoTime()NANOSECONDS.sleep(fixedDelay+rnd.nextLong()%randMod); } 4、具有时间限制的活动,定时锁同样有用.超时后程序提前返回. public boolean trySendOnSharedLine(String message,longtimeout,TimeUnit unit) throwsInterruptedException{ longnanosToLock=unit.toNanos(timeout)-estimatedNanosToSend(message); if (!lock.tryLock(nanosToLock,NANOSECONDS)) return false; try{ return sendOnSharedLine(message); }finally{lock.unlock();} } 5、一个可中断的锁可以响应中断,能取消。 public boolean sendOnSharedLine(Stringmessage) throws InterruptedException{ lock.lockInterruptibly(); try{ return cancellableSendOnSharedLine(message); }finally{ lock.unlock(); } } private boolean cancellableSendOnSharedLine(String message) throwsInterruptedException{...} }
楼上你那个是休眠,要中断的话,自己定时来启用sleep。
Thread.sleep(long time);休眠time ;以毫秒为单位

5,Java中LocktryLocklockInterruptibly有什么区别

Java中Lock,tryLock,lockInterruptibly的区别如下:一、 lock()方法使用lock()获取锁,若获取成功,标记下是该线程获取到了锁(用于锁重入),然后返回。若获取失败,这时跑一个for循环,循环中先将线程阻塞放入等待队列,当被调用signal()时线程被唤醒,这时进行锁竞争(因为默认使用的是非公平锁),如果此时用CAS获取到了锁那么就返回,如果没获取到那么再次放入等待队列,等待唤醒,如此循环。其间就算外部调用了interrupt(),循环也会继续走下去。一直到当前线程获取到了这个锁,此时才处理interrupt标志,若有,则执行 Thread.currentThread().interrupt(),结果如何取决于外层的处理。lock()最终执行的方法如下:[java] view plain copyfinal boolean acquireQueued(final Node node, int arg) boolean failed = true;try boolean interrupted = false;for (;;) final Node p = node.predecessor();if (p == head && tryAcquire(arg)) setHead(node);p.next = null; // help GCfailed = false;return interrupted; //获取成功返回interrupted标志}// 只修改标志位,不做其他处理if (shouldParkAfterFailedAcquire(p, node) && <strong>parkAndCheckInterrupt()</strong>)interrupted = true;}} finally if (failed)cancelAcquire(node);} } 其中parkAndCheckInterrupt()调用了LockSupport.park(),该方法使用Unsafe类将进程阻塞并放入等待队列,等待唤醒,和await()有点类似。可以看到循环中检测到了interrupt标记,但是仅做 interrupted = true 操作,直到获取到了锁,才return interrupted,然后处理如下[java] view plain copypublic final void acquire(int arg) if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg))selfInterrupt(); // 执行Thread.currentThread().interrupt()} 二、 lockInterruptibly()方法和lock()相比,lockInterruptibly()只有略微的修改,for循环过程中,如果检测到interrupt标志为true,则立刻抛出InterruptedException异常,这时程序变通过异常直接返回到最外层了,又外层继续处理,因此使用lockInterruptibly()时必须捕捉异常。lockInterruptibly()最终执行的方法如下:[java] view plain copyprivate void doAcquireInterruptibly(int arg)throws InterruptedException final Node node = addWaiter(Node.EXCLUSIVE);boolean failed = true;try for (;;) final Node p = node.predecessor();if (p == head && tryAcquire(arg)) setHead(node);p.next = null; // help GCfailed = false;return; //获取成功返回}if (shouldParkAfterFailedAcquire(p, node) &&parkAndCheckInterrupt())throw new InterruptedException(); //直接抛出异常}} finally if (failed)cancelAcquire(node);} } 三、 tryLock()方法使用tryLock()尝试获取锁,若获取成功,标记下是该线程获取到了锁,然后返回true;若获取失败,此时直接返回false,告诉外层没有获取到锁,之后的操作取决于外层,代码如下:[java] view plain copyfinal boolean nonfairTryAcquire(int acquires) final Thread current = Thread.currentThread();int c = getState();if (c == 0) if (compareAndSetState(0, acquires)) setExclusiveOwnerThread(current);return true;}}else if (current == getExclusiveOwnerThread()) int nextc = c + acquires;if (nextc < 0) // overflowthrow new Error("Maximum lock count exceeded");setState(nextc);return true;}return false; }

6,请教lock和ApplicationLock有什么区别

Java中Lock,tryLock,lockInterruptibly的区别如下:一、 lock()方法使用lock()获取锁,若获取成功,标记下是该线程获取到了锁(用于锁重入),然后返回。若获取失败,这时跑一个for循环,循环中先将线程阻塞放入等待队列,当被调用signal()时线程被唤醒,这时进行锁竞争(因为默认使用的是非公平锁),如果此时用CAS获取到了锁那么就返回,如果没获取到那么再次放入等待队列,等待唤醒,如此循环。其间就算外部调用了interrupt(),循环也会继续走下去。一直到当前线程获取到了这个锁,此时才处理interrupt标志,若有,则执行 Thread.currentThread().interrupt(),结果如何取决于外层的处理。lock()最终执行的方法如下:[java] view plain copyfinal boolean acquireQueued(final Node node, int arg) boolean failed = true; try boolean interrupted = false; for (;;) final Node p = node.predecessor(); if (p == head && tryAcquire(arg)) setHead(node); p.next = null; // help GC failed = false; return interrupted; //获取成功返回interrupted标志 } // 只修改标志位,不做其他处理 if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) interrupted = true; } } finally if (failed) cancelAcquire(node); } } 其中parkAndCheckInterrupt()调用了LockSupport.park(),该方法使用Unsafe类将进程阻塞并放入等待队列,等待唤醒,和await()有点类似。可以看到循环中检测到了interrupt标记,但是仅做 interrupted = true 操作,直到获取到了锁,才return interrupted,然后处理如下[java] view plain copypublic final void acquire(int arg) if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); // 执行Thread.currentThread().interrupt() } 二、 lockInterruptibly()方法和lock()相比,lockInterruptibly()只有略微的修改,for循环过程中,如果检测到interrupt标志为true,则立刻抛出InterruptedException异常,这时程序变通过异常直接返回到最外层了,又外层继续处理,因此使用lockInterruptibly()时必须捕捉异常。lockInterruptibly()最终执行的方法如下:[java] view plain copyprivate void doAcquireInterruptibly(int arg) throws InterruptedException final Node node = addWaiter(Node.EXCLUSIVE); boolean failed = true; try for (;;) final Node p = node.predecessor(); if (p == head && tryAcquire(arg)) setHead(node); p.next = null; // help GC failed = false; return; //获取成功返回 } if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) throw new InterruptedException(); //直接抛出异常 } } finally if (failed) cancelAcquire(node); } } 三、 tryLock()方法使用tryLock()尝试获取锁,若获取成功,标记下是该线程获取到了锁,然后返回true;若获取失败,此时直接返回false,告诉外层没有获取到锁,之后的操作取决于外层,代码如下:[java] view plain copyfinal boolean nonfairTryAcquire(int acquires) final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) if (compareAndSetState(0, acquires)) setExclusiveOwnerThread(current); return true; } } else if (current == getExclusiveOwnerThread()) int nextc = c + acquires; if (nextc < 0) // overflow throw new Error("Maximum lock count exceeded"); setState(nextc); return true; } return false; }
文章TAG:我想在写文件的时候trylock

最近更新

  • 青岛港湾学校电气自动化,青岛各高校综合实力排名出炉!青岛港湾学校电气自动化,青岛各高校综合实力排名出炉!

    我是青岛港学院的学生。青岛港学院怎么样?哎~!青岛广播电视大学、青岛外贸职工大学、青岛理工大学、青岛科技大学、滨海学院、黄海学院、32电子学院、工贸学院、渤海学院青岛职业技术学.....

    知识 日期:2025-03-06

  • 机器人是谁创造的,创造与魔法机器人位置机器人是谁创造的,创造与魔法机器人位置

    外星人是谁提出的猜想机器人?机器人发展历史和最早机器人谁发明的?没有人真的知道它是谁,是谁,但是它发明的时间是有历史记载的!世界上第一个机器人是谁做的?机器人Information机器人概述在.....

    知识 日期:2025-03-06

  • 福州大学电气自动化专业福州大学电气自动化专业

    福州大学电气工科和自动化专业怎么样?福州大学-2/工程和自动化-3/怎么样?福州大学至诚学院能考吗福州大学电气工科及其自动化专业研究生?关于福州大学电气工科及其自动化专业考研福州大学.....

    知识 日期:2025-03-06

  • cv计算机,计算机有哪些级别证书通过哪些途径考试cv计算机,计算机有哪些级别证书通过哪些途径考试

    计算机有哪些级别证书通过哪些途径考试2,CV什么意思3,电脑中CVHOST应有几个4,什么是计算机CCNT5,计算机的级别是怎么分的6,计算机共有几个等级证书1,计算机有哪些级别证书通过哪些途径考试全.....

    知识 日期:2025-03-06

  • 电信公众号电信公众号

    四川的号码是多少电信微信公众四川电信微信公众是四川电信。具体添加方法如下:打开微信,进入微信后台,点击,如何添加四川电信公众Add公众以下工具资料:手机、微信方法步骤:1.打开微信,进入.....

    知识 日期:2025-03-06

  • 中国四小龙,中原四小龙是谁中国四小龙,中原四小龙是谁

    中原四小龙是谁2,中国四小龙除了成龙李小龙还有谁3,中国四小龙是哪四个4,中国四小龙是哪几个5,中国影视中并称四小龙的是哪几位演员6,中国四小龙是那几位1,中原四小龙是谁李小龙狄龙梁小龙成.....

    知识 日期:2025-03-06

  • 自动化哪家公司好些些,三明治工业生产自动化流水线哪家好?自动化哪家公司好些些,三明治工业生产自动化流水线哪家好?

    国内有哪些可靠知名的自动化公司?自动化好的工厂有哪些?汽车生产线哪个公司生产三明治?东莞怡和达自动化股份有限公司推荐东莞怡和达公司深耕自动化设备行业,基于应用场景,规范自动化设备零.....

    知识 日期:2025-03-06

  • 车载网络,什么是车载网络车载网络,什么是车载网络

    什么是车载网络2,车载无线网怎么弄3,车载wifi怎么使用4,汽车网络怎么连接5,车载wifi怎么收费6,汽车上如何安装wifi1,什么是车载网络早期的汽车内部传感器、控制和执行器之间的通讯用点对点的.....

    知识 日期:2025-03-06