網頁

2009年12月20日 星期日

Java Thread

Java 的 Thread 和 Process 一樣,共有五個 state,
分別是 New, Runnable, Running, Waiting/blocked/sleeping, Dead。

New - 當 thread's instance 已經建立,但是尚未呼叫 start(),
此時,這個 thread 仍然稱做 not alive。

(其他的 state 和 Process 幾乎相同,這裡就省略了)


接下來介紹有關操作 thread 所需要呼叫的 method。

start() - Thread's non-static method
將該 thread 從 New state 移至 Runnable state,
至此,該 thread 才成為一個 alive thread。

無論如何,同一個 thread 物件都只能 start() 一次,
否則將會產生 RuntimeException;
然而同一個 Runnable interface,
則可以經由 Thread's Constructor,建立並啟動多個 thread。

yield() - Thread's static method
將目前的 thread 由 Running state 移至 Runnable,
並且由 Runnable state 中,
選一 "相同" priority 的 thread 進入 Running state,
故有可能會選到原先的 thread。

由於 JVM 對於 priority 的實作未必確實為 1~10,
可能會有多個設定值對應到同一個 priority 的情形,
所以需要特別注意。

sleep() - Thread's static method
將目前的 thread 由 Running state 移至 Sleeping,
並等待指定的時間後,才會進入 Runnable。

並不是時間一到立刻進入 Running,
所以通常該 thread 的休息時間會較長於指定的時間。

若是在 synchronize block 中呼叫 sleep(),
則 thread 並不會釋放自己所擁有的資源。

join() - Thread's non-static method
暫停目前 thread 的執行,並等待指定的 thread 執行完畢後,
此 thread 才會回到 runnable state。

以下三個指令都必須在 synchronize block 中才可呼叫。

wait() - Object's non-static method
目前 thread 進入 Waiting,暫時釋放指定的資源。

當此 thread 經由 notify() or notifyAll() 叫醒後,
會送出 InterruptedException()。

另外,wait() 也有 over-loading 的版本,
提供最長等待時間作為參數。

notify() - Object's non-static method
叫醒某個正等待此物件之 thread。

叫醒的順序與 thread 進入 Wainting 的時間無關。

notifyAll() - Object's non-static method
叫醒所有正在等待此物件之 thread。

註: notify 與 notifyAll 所叫醒的 thread 只是回到 runnable,
而並不會立刻執行。          

沒有留言:

張貼留言