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

首頁 > 廠商 > 知識 > trylock,我想在寫文件的時候將這個文件鎖定不讓其他線程或者程序操作該

trylock,我想在寫文件的時候將這個文件鎖定不讓其他線程或者程序操作該

來源:整理 時間:2025-03-06 22:16:56 編輯:智能門戶 手機版

本文目錄一覽

1,我想在寫文件的時候將這個文件鎖定不讓其他線程或者程序操作該

兩種方式第一種是使用RandomAccessFile,創(chuàng)建RandomAccessFile對象時使用rws參數(shù),如——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()方法也可以獲取文件鎖,區(qū)別是lock()方法是阻塞式的,只有成功獲取到文件鎖才能進行后續(xù)操作,否則一直等待。

我想在寫文件的時候將這個文件鎖定不讓其他線程或者程序操作該

2,JAVA 如何防止同時操作一個文件

服務端用一個Map來記錄用戶操作的文件。。 當一個用戶請求操作file1文件的時候,就用: if(map.push(file,user1)) System.out.println("success"); 根據能否push到map里面,來表示該文件是否正在被使用。。 如果一個用戶操作完該文件,調用map.remove(file1)即可
windows 會自動控制。linux系統(tǒng),你就用同步方法吧,把對文件的操作寫到同步方法里面。
我們通過RandomAccessFile這個隨機讀取流來操作文件速度上面會有一點慢、但不是極其大的文件一般可以忽略。 我們通過FileChannel對象來獲得鎖 Trylock 與lock方法 tryLock()是非阻塞式的,它設法獲取鎖,但如果不能獲得,例如因為其他一些進程已經持有相同的鎖,而且不共享時,它將直接從方法調用返回。 lock()是阻塞式的,它要阻塞進程直到鎖可以獲得,或調用lock()的線程中斷,或調用lock()的通道關閉。 對獨占鎖和共享鎖的支持必須由底層的操作系統(tǒng)提供。鎖的類型可以通過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,則程序不能繼續(xù)執(zhí)行臨界區(qū)代碼。如果執(zhí)行了,這個程序很可能會出現(xiàn)錯誤的結果。你的代碼中就是不論是否拿到lock 都會執(zhí)行臨界區(qū)。

關于ReentrantLock類的trylock的使用問題

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

1、從JAVA5.0開始,提供了新的選擇:ReentrantLock。2、可定時和可輪詢的鎖獲取模式由tryLock方法實現(xiàn)。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有什么區(qū)別

Java中Lock,tryLock,lockInterruptibly的區(qū)別如下:一、 lock()方法使用lock()獲取鎖,若獲取成功,標記下是該線程獲取到了鎖(用于鎖重入),然后返回。若獲取失敗,這時跑一個for循環(huán),循環(huán)中先將線程阻塞放入等待隊列,當被調用signal()時線程被喚醒,這時進行鎖競爭(因為默認使用的是非公平鎖),如果此時用CAS獲取到了鎖那么就返回,如果沒獲取到那么再次放入等待隊列,等待喚醒,如此循環(huán)。其間就算外部調用了interrupt(),循環(huán)也會繼續(xù)走下去。一直到當前線程獲取到了這個鎖,此時才處理interrupt標志,若有,則執(zhí)行 Thread.currentThread().interrupt(),結果如何取決于外層的處理。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標志}// 只修改標志位,不做其他處理if (shouldParkAfterFailedAcquire(p, node) && <strong>parkAndCheckInterrupt()</strong>)interrupted = true;}} finally if (failed)cancelAcquire(node);} } 其中parkAndCheckInterrupt()調用了LockSupport.park(),該方法使用Unsafe類將進程阻塞并放入等待隊列,等待喚醒,和await()有點類似??梢钥吹窖h(huán)中檢測到了interrupt標記,但是僅做 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標志為true,則立刻拋出InterruptedException異常,這時程序變通過異常直接返回到最外層了,又外層繼續(xù)處理,因此使用lockInterruptibly()時必須捕捉異常。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()嘗試獲取鎖,若獲取成功,標記下是該線程獲取到了鎖,然后返回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有什么區(qū)別

Java中Lock,tryLock,lockInterruptibly的區(qū)別如下:一、 lock()方法使用lock()獲取鎖,若獲取成功,標記下是該線程獲取到了鎖(用于鎖重入),然后返回。若獲取失敗,這時跑一個for循環(huán),循環(huán)中先將線程阻塞放入等待隊列,當被調用signal()時線程被喚醒,這時進行鎖競爭(因為默認使用的是非公平鎖),如果此時用CAS獲取到了鎖那么就返回,如果沒獲取到那么再次放入等待隊列,等待喚醒,如此循環(huán)。其間就算外部調用了interrupt(),循環(huán)也會繼續(xù)走下去。一直到當前線程獲取到了這個鎖,此時才處理interrupt標志,若有,則執(zhí)行 Thread.currentThread().interrupt(),結果如何取決于外層的處理。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標志 } // 只修改標志位,不做其他處理 if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) interrupted = true; } } finally if (failed) cancelAcquire(node); } } 其中parkAndCheckInterrupt()調用了LockSupport.park(),該方法使用Unsafe類將進程阻塞并放入等待隊列,等待喚醒,和await()有點類似??梢钥吹窖h(huán)中檢測到了interrupt標記,但是僅做 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標志為true,則立刻拋出InterruptedException異常,這時程序變通過異常直接返回到最外層了,又外層繼續(xù)處理,因此使用lockInterruptibly()時必須捕捉異常。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()嘗試獲取鎖,若獲取成功,標記下是該線程獲取到了鎖,然后返回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電子學院、工貿學院、渤海學院青島職業(yè)技術學.....

    知識 日期:2025-03-06

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

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

    知識 日期:2025-03-06

  • 福州大學電氣自動化專業(yè)福州大學電氣自動化專業(yè)

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

    知識 日期: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

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

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

    知識 日期:2025-03-06

  • 車載網絡,什么是車載網絡車載網絡,什么是車載網絡

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

    知識 日期:2025-03-06