close


進入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.


原文摘自:朱色虫居

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 angledark0123 的頭像
    angledark0123

    CONY的世界

    angledark0123 發表在 痞客邦 留言(0) 人氣()