2007/10/28

Java Thread Notes

進入waiting queue的兩種可能:
1. 被lock (synchronized block) 擋在critical section外面.
2. call wait() method.


離開waiting queure的可能:
1.call notify() method.
2.call notifyAll() method.
3.call interrupt() method.
4.time out occur. (透過call wait( long time ) 來實現)


yield() v.s. sleep() v.s. wait() v.s. join()
1. yield() thread 沒有離開monitor,只是暫時將執行權交給其它的thread (content switch ?)
2. sleep(1000),thread 沒有離開monitor, 只是暫停執行1000ms.
3. wait(1000) ,thread離開monitor, 移到waiting queue, 若1000ms後仍未被喚醒, 便離開waiting queue, 重新競爭lock;若無設time out,即wait(),則移至waiting queue等待。直到notify(), notifyAll(), interrupt() 被呼叫時,才會便離開waiting queue, 重新競爭lock.
4. join(),直到此thread執行完,才將執行權讓出。也可設time out。


interrupt() 把沈睡的thread半途打醒.
1. 用來中斷wait(), sleep(), join()等狀態的thread.
2. 會從wait(), sleep(), join() 中丟出InterruptedException, thread的控制權便會轉入catch block.
3. thread wati()時,會離開monitor,移到waiting queue,所以當wait狀態的thread被呼叫interrupt()時,需先重新搶到lock,才會丟出interruptedException. 取得lock前都不會丟出interruptedException.
4. wait(), sleep(), join()都會不斷檢查interrupt status,而interrupt()便是把interrupt status設為true,當wait(), sleep(), join()發現interrupt status為true時,便丟出interruptedException.
5. isInterrupted() 可以回傳interrupt status為何.
6. interrupted() 除了回傳interrupt status外,並將interrupt status設為false.


interrupt() v.s. notify() and notifyAll()
1.notify()及notifyAll()是喚醒在waiting queue的thread.
2.interrupt()是直接中斷sleep() , wait(), join()狀態的thread.


 

3 comments:

  1. [...] java tread notes Posted on December 5, 2007 by randomzone http://redbug.twbbs.org/index.php/2007/10/27/322 [...]

    ReplyDelete
  2. 最近正在研究Java Thread,希望借轉這篇文章到我的Blog

    http://kuroridoplayer.blogspot.com/

    如果版大不希望我轉的話請告知,我會馬上刪除,非常感謝。

    ReplyDelete
  3. 最近正在研究Java Thread,希望借轉這篇文章到我的Blog

    http://www.wretch.cc/blog/Crystal0123/27390180

    如果版大不希望我轉的話請告知,我會馬上刪除,非常感謝。

    ReplyDelete