java中線程的基本方法的熟練使用是精通多線程編程的必經之路,線程相關的基本方法有wait
,notify
,notifyAll
,sleep
,join
,yield
等,本文淺要的介紹一下它們的使用方式。
線程的狀態圖
java將操作系統中的就緒和運行兩種狀態統稱爲可運行狀態,java中線程的狀態可以認爲有以上六種。
wait
調用該方法的線程進入WAITING狀態,只有等待另外線程的通知或被中斷纔會返回,需要注意的是調用wait()方法後,會釋放對象的鎖。
因此,wait方法一般用在同步方法或同步代碼塊中。
sleep
sleep導致當前線程休眠,與wait方法不同的是sleep不會釋放當前佔有的鎖,sleep(long)會導致線程進入TIMED-WATING狀態,而wait()方法會導致當前線程進入WATING狀態
yield
yield會使當前線程讓出CPU執行時間片,與其他線程一起重新競爭CPU時間片。一般情況下,優先級高的線程有更大的可能性成功競爭得到CPU時間片,但這又不是絕對的,有的操作系統對線程優先級並不敏感。
interrupt
中斷一個線程,其本意是給這個線程一個通知信號,會影響這個線程內部的一箇中斷標識位。這個線程本身並不會因此而改變狀態(如阻塞,終止等)。
1.調用interrupt()方法並不會中斷一個正在運行的線程。也就是說處於Running
狀態的線程並不會因爲被中斷而被終止,僅僅改變了內部維護的中斷標識位而已。
2.若調用sleep()而使線程處於TIMED-WATING狀態,這時調用interrupt()方法,會拋出InterruptedException
,從而使線程提前結束TIMED-WATING狀態。
3.許多聲明拋出InterruptedException
的方法(如Thread.sleep(long mills方法)),拋出異常前,都會清除中斷標識位,所以拋出異常後,調用isInterrupted()
方法將會返回false。
4.中斷狀態是線程固有的一個標識位,可以通過此標識位安全的終止線程。比如,你想終止一個線程thread的時候,可以調用thread.interrupt()
方法,在線程的run方法內部可以根據thread.isInterrupted()
的值來優雅的終止線程。當然,你可以在線程內部自己維護一個boolean變量來控制線程的運行和終止。
現在,我們看一下源碼裏這個方法是怎麼說明的。
/**
* Interrupts this thread.
* 中斷這個線程
*
* <p> Unless the current thread is interrupting itself, which is
* always permitted, the {@link #checkAccess() checkAccess} method
* of this thread is invoked, which may cause a {@link
* SecurityException} to be thrown.
* 如果不是當前線程中斷自身,這經常是被允許的。不過要檢查安全性,
* 可能會拋出安全異常的。
*
* <p> If this thread is blocked in an invocation of the {@link
* Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
* Object#wait(long, int) wait(long, int)} methods of the {@link Object}
* class, or of the {@link #join()}, {@link #join(long)}, {@link
* #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
* methods of this class, then its interrupt status will be cleared and it
* will receive an {@link InterruptedException}.
* 如果中斷的線程由於調用一個Object對象的多個wait方法或者當前對象的
* join,sleep方法而正處於阻塞狀態(僅表示沒有獲得CPU的時間片執行,不表示
* 線程的BLOCKED狀態)。那麼它的中斷狀態將被清除(復位),而且它會收到中
* 斷異常。
*
* <p> If this thread is blocked in an I/O operation upon an {@link
* java.nio.channels.InterruptibleChannel InterruptibleChannel}
* then the channel will be closed, the thread's interrupt
* status will be set, and the thread will receive a {@link
* java.nio.channels.ClosedByInterruptException}.
*
* <p> If this thread is blocked in a {@link java.nio.channels.Selector}
* then the thread's interrupt status will be set and it will return
* immediately from the selection operation, possibly with a non-zero
* value, just as if the selector's {@link
* java.nio.channels.Selector#wakeup wakeup} method were invoked.
*
* <p> If none of the previous conditions hold then this thread's interrupt
* status will be set. </p>
* 如果上述的條件都沒有比中的話,那麼這個線程的中斷標誌位將被設置。
*
* <p> Interrupting a thread that is not alive need not have any effect.
* 中斷一個不存活的線程(未啓動或已結束)不會有任何影響
*
* @throws SecurityException
* if the current thread cannot modify this thread
*
* @revised 6.0
* @spec JSR-51
*/
public void interrupt() {
//檢查當前線程對this線程的安全權限,如果不允許修改,會拋出異常
if (this != Thread.currentThread())
checkAccess();
//加鎖同步
synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
interrupt0(); // Just to set the interrupt flag
b.interrupt(this);
return;
}
}
interrupt0(); //設置標識位,本地方法
}
基本很簡單,首先檢查當前線程對this線程的安全權限,如果不允許修改,會拋出異常。隨後加鎖同步設置中斷標識位。儘管方法聲明中有詳細說明,但是代碼中看不出來,處於wating狀態的線程被中斷後,中斷標識會復位。我認爲這是靠本地代碼interrupt0實現的。
join
在線程A上下文中執行了線程B.join()語句,其含義是線程B執行結束後,join()方法纔會返回,線程A纔可繼續執行。
舉個例子,如果你創建了10個線程,同時調用start()方法執行線程,但是你想讓它們有序執行,就可以使用join來輔助完成。代碼如下:
/***
* 此示例中10個線程在執行時,,需要等待前一個線程執行完;
* 比如線程0要等待main線程執行完
* 線程9要等到線程8執行完
*
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
Thread previous = Thread.currentThread();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(new Dimon(previous), String.valueOf(i));
thread.start();
previous = thread;
}
TimeUnit.SECONDS.sleep(5);
System.out.println(Thread.currentThread().getName() + "terminate");
}
static class Dimon implements Runnable{
private Thread thread;
public Dimon(Thread thread){
this.thread = thread;
}
@Override
public void run() {
try {
thread.join();
}catch (Exception e){
}
System.out.println( Thread.currentThread().getName() + ":terminate" );
}
}