Re: [問題] 利用Thread呼叫JNotify無反應
※ 引述《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
03/29 22:42, 2F
推
03/30 17:56, , 3F
03/30 17:56, 3F
討論串 (同標題文章)
完整討論串 (本文為第 2 之 2 篇):