强奸久久久久久久|草草浮力在线影院|手机成人无码av|亚洲精品狼友视频|国产国模精品一区|久久成人中文字幕|超碰在线视屏免费|玖玖欧洲一区二区|欧美精品无码一区|日韩无遮一区二区

首頁 > 廠商 > 知識(shí) > trylock,我想在寫文件的時(shí)候?qū)⑦@個(gè)文件鎖定不讓其他線程或者程序操作該

trylock,我想在寫文件的時(shí)候?qū)⑦@個(gè)文件鎖定不讓其他線程或者程序操作該

來源:整理 時(shí)間:2025-03-06 22:16:56 編輯:智能門戶 手機(jī)版

本文目錄一覽

1,我想在寫文件的時(shí)候?qū)⑦@個(gè)文件鎖定不讓其他線程或者程序操作該

兩種方式第一種是使用RandomAccessFile,創(chuàng)建RandomAccessFile對(duì)象時(shí)使用rws參數(shù),如——RandomAccessFile raf = new RandomAccessFile(new File("c:/test.txt"), "rws");即以鎖定方式對(duì)文件進(jìn)行寫入,就是所謂的獨(dú)占方式。第二種是使用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()方法獲取文件鎖,它還有一個(gè)lock()方法也可以獲取文件鎖,區(qū)別是lock()方法是阻塞式的,只有成功獲取到文件鎖才能進(jìn)行后續(xù)操作,否則一直等待。

我想在寫文件的時(shí)候?qū)⑦@個(gè)文件鎖定不讓其他線程或者程序操作該

2,JAVA 如何防止同時(shí)操作一個(gè)文件

服務(wù)端用一個(gè)Map來記錄用戶操作的文件。。 當(dāng)一個(gè)用戶請(qǐng)求操作file1文件的時(shí)候,就用: if(map.push(file,user1)) System.out.println("success"); 根據(jù)能否push到map里面,來表示該文件是否正在被使用。。 如果一個(gè)用戶操作完該文件,調(diào)用map.remove(file1)即可
windows 會(huì)自動(dòng)控制。linux系統(tǒng),你就用同步方法吧,把對(duì)文件的操作寫到同步方法里面。
我們通過RandomAccessFile這個(gè)隨機(jī)讀取流來操作文件速度上面會(huì)有一點(diǎn)慢、但不是極其大的文件一般可以忽略。 我們通過FileChannel對(duì)象來獲得鎖 Trylock 與lock方法 tryLock()是非阻塞式的,它設(shè)法獲取鎖,但如果不能獲得,例如因?yàn)槠渌恍┻M(jìn)程已經(jīng)持有相同的鎖,而且不共享時(shí),它將直接從方法調(diào)用返回。 lock()是阻塞式的,它要阻塞進(jìn)程直到鎖可以獲得,或調(diào)用lock()的線程中斷,或調(diào)用lock()的通道關(guān)閉。 對(duì)獨(dú)占鎖和共享鎖的支持必須由底層的操作系統(tǒng)提供。鎖的類型可以通過FileLock.isShared()進(jìn)行查詢。另外,我們不能獲取緩沖器上的鎖,只能是通道上的。 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("有其他線程正在操作該文件,當(dāng)前線程休眠1000毫秒"); sleep(1000); } }

JAVA 如何防止同時(shí)操作一個(gè)文件

3,關(guān)于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必須注意:如果這個(gè)方法返回false,則程序不能繼續(xù)執(zhí)行臨界區(qū)代碼。如果執(zhí)行了,這個(gè)程序很可能會(huì)出現(xiàn)錯(cuò)誤的結(jié)果。你的代碼中就是不論是否拿到lock 都會(huì)執(zhí)行臨界區(qū)。

關(guān)于ReentrantLock類的trylock的使用問題

4,java 線程怎么實(shí)現(xiàn)定時(shí)中斷

1、從JAVA5.0開始,提供了新的選擇:ReentrantLock。2、可定時(shí)和可輪詢的鎖獲取模式由tryLock方法實(shí)現(xiàn)。3、使用tryLock試圖獲得的鎖如果不能同時(shí)獲得,就回退,并重新嘗試。休眠時(shí)間由一個(gè)特定組件管理。(下面的代碼完成轉(zhuǎn)帳)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、具有時(shí)間限制的活動(dòng),定時(shí)鎖同樣有用.超時(shí)后程序提前返回. 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、一個(gè)可中斷的鎖可以響應(yīng)中斷,能取消。 public boolean sendOnSharedLine(Stringmessage) throws InterruptedException{ lock.lockInterruptibly(); try{ return cancellableSendOnSharedLine(message); }finally{ lock.unlock(); } } private boolean cancellableSendOnSharedLine(String message) throwsInterruptedException{...} }
樓上你那個(gè)是休眠,要中斷的話,自己定時(shí)來啟用sleep。
Thread.sleep(long time);休眠time ;以毫秒為單位

5,Java中LocktryLocklockInterruptibly有什么區(qū)別

Java中Lock,tryLock,lockInterruptibly的區(qū)別如下:一、 lock()方法使用lock()獲取鎖,若獲取成功,標(biāo)記下是該線程獲取到了鎖(用于鎖重入),然后返回。若獲取失敗,這時(shí)跑一個(gè)for循環(huán),循環(huán)中先將線程阻塞放入等待隊(duì)列,當(dāng)被調(diào)用signal()時(shí)線程被喚醒,這時(shí)進(jìn)行鎖競爭(因?yàn)槟J(rèn)使用的是非公平鎖),如果此時(shí)用CAS獲取到了鎖那么就返回,如果沒獲取到那么再次放入等待隊(duì)列,等待喚醒,如此循環(huán)。其間就算外部調(diào)用了interrupt(),循環(huán)也會(huì)繼續(xù)走下去。一直到當(dāng)前線程獲取到了這個(gè)鎖,此時(shí)才處理interrupt標(biāo)志,若有,則執(zhí)行 Thread.currentThread().interrupt(),結(jié)果如何取決于外層的處理。lock()最終執(zhí)行的方法如下:[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標(biāo)志}// 只修改標(biāo)志位,不做其他處理if (shouldParkAfterFailedAcquire(p, node) && <strong>parkAndCheckInterrupt()</strong>)interrupted = true;}} finally if (failed)cancelAcquire(node);} } 其中parkAndCheckInterrupt()調(diào)用了LockSupport.park(),該方法使用Unsafe類將進(jìn)程阻塞并放入等待隊(duì)列,等待喚醒,和await()有點(diǎn)類似。可以看到循環(huán)中檢測到了interrupt標(biāo)記,但是僅做 interrupted = true 操作,直到獲取到了鎖,才return interrupted,然后處理如下[java] view plain copypublic final void acquire(int arg) if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg))selfInterrupt(); // 執(zhí)行Thread.currentThread().interrupt()} 二、 lockInterruptibly()方法和lock()相比,lockInterruptibly()只有略微的修改,for循環(huán)過程中,如果檢測到interrupt標(biāo)志為true,則立刻拋出InterruptedException異常,這時(shí)程序變通過異常直接返回到最外層了,又外層繼續(xù)處理,因此使用lockInterruptibly()時(shí)必須捕捉異常。lockInterruptibly()最終執(zhí)行的方法如下:[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()嘗試獲取鎖,若獲取成功,標(biāo)記下是該線程獲取到了鎖,然后返回true;若獲取失敗,此時(shí)直接返回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,請(qǐng)教lock和ApplicationLock有什么區(qū)別

Java中Lock,tryLock,lockInterruptibly的區(qū)別如下:一、 lock()方法使用lock()獲取鎖,若獲取成功,標(biāo)記下是該線程獲取到了鎖(用于鎖重入),然后返回。若獲取失敗,這時(shí)跑一個(gè)for循環(huán),循環(huán)中先將線程阻塞放入等待隊(duì)列,當(dāng)被調(diào)用signal()時(shí)線程被喚醒,這時(shí)進(jìn)行鎖競爭(因?yàn)槟J(rèn)使用的是非公平鎖),如果此時(shí)用CAS獲取到了鎖那么就返回,如果沒獲取到那么再次放入等待隊(duì)列,等待喚醒,如此循環(huán)。其間就算外部調(diào)用了interrupt(),循環(huán)也會(huì)繼續(xù)走下去。一直到當(dāng)前線程獲取到了這個(gè)鎖,此時(shí)才處理interrupt標(biāo)志,若有,則執(zhí)行 Thread.currentThread().interrupt(),結(jié)果如何取決于外層的處理。lock()最終執(zhí)行的方法如下:[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標(biāo)志 } // 只修改標(biāo)志位,不做其他處理 if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) interrupted = true; } } finally if (failed) cancelAcquire(node); } } 其中parkAndCheckInterrupt()調(diào)用了LockSupport.park(),該方法使用Unsafe類將進(jìn)程阻塞并放入等待隊(duì)列,等待喚醒,和await()有點(diǎn)類似。可以看到循環(huán)中檢測到了interrupt標(biāo)記,但是僅做 interrupted = true 操作,直到獲取到了鎖,才return interrupted,然后處理如下[java] view plain copypublic final void acquire(int arg) if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); // 執(zhí)行Thread.currentThread().interrupt() } 二、 lockInterruptibly()方法和lock()相比,lockInterruptibly()只有略微的修改,for循環(huán)過程中,如果檢測到interrupt標(biāo)志為true,則立刻拋出InterruptedException異常,這時(shí)程序變通過異常直接返回到最外層了,又外層繼續(xù)處理,因此使用lockInterruptibly()時(shí)必須捕捉異常。lockInterruptibly()最終執(zhí)行的方法如下:[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()嘗試獲取鎖,若獲取成功,標(biāo)記下是該線程獲取到了鎖,然后返回true;若獲取失敗,此時(shí)直接返回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:我想在寫文件的時(shí)候trylock

最近更新

  • 青島港灣學(xué)校電氣自動(dòng)化,青島各高校綜合實(shí)力排名出爐!青島港灣學(xué)校電氣自動(dòng)化,青島各高校綜合實(shí)力排名出爐!

    我是青島港學(xué)院的學(xué)生。青島港學(xué)院怎么樣?哎~!青島廣播電視大學(xué)、青島外貿(mào)職工大學(xué)、青島理工大學(xué)、青島科技大學(xué)、濱海學(xué)院、黃海學(xué)院、32電子學(xué)院、工貿(mào)學(xué)院、渤海學(xué)院青島職業(yè)技術(shù)學(xué).....

    知識(shí) 日期:2025-03-06

  • 機(jī)器人是誰創(chuàng)造的,創(chuàng)造與魔法機(jī)器人位置機(jī)器人是誰創(chuàng)造的,創(chuàng)造與魔法機(jī)器人位置

    外星人是誰提出的猜想機(jī)器人?機(jī)器人發(fā)展歷史和最早機(jī)器人誰發(fā)明的?沒有人真的知道它是誰,是誰,但是它發(fā)明的時(shí)間是有歷史記載的!世界上第一個(gè)機(jī)器人是誰做的?機(jī)器人Information機(jī)器人概述在.....

    知識(shí) 日期:2025-03-06

  • 福州大學(xué)電氣自動(dòng)化專業(yè)福州大學(xué)電氣自動(dòng)化專業(yè)

    福州大學(xué)電氣工科和自動(dòng)化專業(yè)怎么樣?福州大學(xué)-2/工程和自動(dòng)化-3/怎么樣?福州大學(xué)至誠學(xué)院能考嗎福州大學(xué)電氣工科及其自動(dòng)化專業(yè)研究生?關(guān)于福州大學(xué)電氣工科及其自動(dòng)化專業(yè)考研福州大學(xué).....

    知識(shí) 日期:2025-03-06

  • cv計(jì)算機(jī),計(jì)算機(jī)有哪些級(jí)別證書通過哪些途徑考試cv計(jì)算機(jī),計(jì)算機(jī)有哪些級(jí)別證書通過哪些途徑考試

    計(jì)算機(jī)有哪些級(jí)別證書通過哪些途徑考試2,CV什么意思3,電腦中CVHOST應(yīng)有幾個(gè)4,什么是計(jì)算機(jī)CCNT5,計(jì)算機(jī)的級(jí)別是怎么分的6,計(jì)算機(jī)共有幾個(gè)等級(jí)證書1,計(jì)算機(jī)有哪些級(jí)別證書通過哪些途徑考試全.....

    知識(shí) 日期:2025-03-06

  • 電信公眾號(hào)電信公眾號(hào)

    四川的號(hào)碼是多少電信微信公眾四川電信微信公眾是四川電信。具體添加方法如下:打開微信,進(jìn)入微信后臺(tái),點(diǎn)擊,如何添加四川電信公眾Add公眾以下工具資料:手機(jī)、微信方法步驟:1.打開微信,進(jìn)入.....

    知識(shí) 日期:2025-03-06

  • 中國四小龍,中原四小龍是誰中國四小龍,中原四小龍是誰

    中原四小龍是誰2,中國四小龍除了成龍李小龍還有誰3,中國四小龍是哪四個(gè)4,中國四小龍是哪幾個(gè)5,中國影視中并稱四小龍的是哪幾位演員6,中國四小龍是那幾位1,中原四小龍是誰李小龍狄龍梁小龍成.....

    知識(shí) 日期:2025-03-06

  • 自動(dòng)化哪家公司好些些,三明治工業(yè)生產(chǎn)自動(dòng)化流水線哪家好?自動(dòng)化哪家公司好些些,三明治工業(yè)生產(chǎn)自動(dòng)化流水線哪家好?

    國內(nèi)有哪些可靠知名的自動(dòng)化公司?自動(dòng)化好的工廠有哪些?汽車生產(chǎn)線哪個(gè)公司生產(chǎn)三明治?東莞怡和達(dá)自動(dòng)化股份有限公司推薦東莞怡和達(dá)公司深耕自動(dòng)化設(shè)備行業(yè),基于應(yīng)用場景,規(guī)范自動(dòng)化設(shè)備零.....

    知識(shí) 日期:2025-03-06

  • 車載網(wǎng)絡(luò),什么是車載網(wǎng)絡(luò)車載網(wǎng)絡(luò),什么是車載網(wǎng)絡(luò)

    什么是車載網(wǎng)絡(luò)2,車載無線網(wǎng)怎么弄3,車載wifi怎么使用4,汽車網(wǎng)絡(luò)怎么連接5,車載wifi怎么收費(fèi)6,汽車上如何安裝wifi1,什么是車載網(wǎng)絡(luò)早期的汽車內(nèi)部傳感器、控制和執(zhí)行器之間的通訊用點(diǎn)對(duì)點(diǎn)的.....

    知識(shí) 日期:2025-03-06

相關(guān)文章