Re: [問題] 利用Thread呼叫JNotify無反應

看板java作者 (十年~)時間12年前 (2013/03/29 13:31), 編輯推噓3(300)
留言3則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《KOFXI ()》之銘言: : 我推測應該是監測檔案的 Thread 已經執行完畢 , 進入結束狀態 : 導致根本沒有做監測檔案的動作 : 所以解決方式是呼叫 addWatch 後加入一個迴圈 : 該迴圈判斷目前Thread是否被中斷,如果沒有就一直跑無窮迴圈 : 所以你可以試著這樣改改看(目前我測試是OK的) : ThreadForJNotify.java : ---------------------------------------------------------------------- : public void run() { : try { : //省略前面資料設定部分.... : int watchID = JNotify.addWatch(path,mask,watchSubtree,new Listener()) ; : //當外部呼叫該 Thread interrupt() 函式會得到 true : while(interrupted()) { : //釋放資源 : JNotify.removeWatch(watchID) ; : } : } : catch(Exception e) { : e.printStackTrace() ; : } : } 這段碼並沒有符合你描述的做法,假如 JNotify.addWatch 不是 blocking 操作, 那麼那個 while loop 一下子就跳離了(由於 thread 原本就不是在 interrupted 狀態)。 我想你的意思應該是 public void run() { int watchID = JNotify.addWatch(path,mask,watchSubtree,new Listener()); while (!Thread.interrupted()); JNotify.removeWatch(watchID); } 不過不建議這樣子做,因為這樣子只是徒耗 CPU 運算能力。 如果真有需要延後一個 thread 結束,又不想浪費運算資源,建議透過 synchronization 機制去做。 例如: public void run() { int watchID = JNotify.addWatch(path,mask,watchSubtree,new Listener()); synchronized (Thread.currentThread()) { try { Thread.currentThread().wait(); } catch (InterruptedException ex) {} } JNotify.removeWatch(watchID); } 想要停止運行上面 run method 的 thread,可對該 thread 執行 interrupt 或 notify 操作。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 1.172.233.10

03/29 22:13, , 1F
歐..這我到沒想到 多謝指教啦!!
03/29 22:13, 1F

03/29 22:42, , 2F
剛剛按照你說的測試 進入wait不用notify就可以偵測到了
03/29 22:42, 2F

03/30 17:56, , 3F
非常感謝你們兩位的建議,小弟受益良多,非常謝謝!!
03/30 17:56, 3F
文章代碼(AID): #1HLPUq_V (java)
文章代碼(AID): #1HLPUq_V (java)