Java Thread.join()方法
阿新 • • 發佈:2018-12-31
join()方法:讓主執行緒等待它的子執行緒死亡。即在一個執行緒中啟動新的執行緒,如果子執行緒呼叫了join方法,主執行緒會等子執行緒死亡後才會繼續往下執行。
例子:
public class ThreadJoin extends Thread{ public void run() { try{ System.out.println("join is start"); for(int i = 0;i<10;i++){ Thread.sleep(1000); System.out.println("thread is run:"+i); } System.out.println("join is end"); }catch(Exception e){ e.printStackTrace(); } } public static void main(String[] args) throws Exception { ThreadJoin threadJoin = new ThreadJoin(); threadJoin.start(); threadJoin.join(); System.out.println("main is end"); } }
結果:
join is start
thread is run:0
thread is run:1
thread is run:2
thread is run:3
thread is run:4
thread is run:5
thread is run:6
thread is run:7
thread is run:8
thread is run:9
join is end
main is end
從結果中可以看出,只有在子執行緒執行完之後,main執行緒才會繼續往下執行。
分析:從原始碼可以看出,程式通過isAlive來判斷子執行緒是否存活者,如果ture,則主執行緒進入阻塞。wait(0)表示當前持有鎖的執行緒進入阻塞,而join()方法是在主執行緒中執行的,所以主執行緒進入等待,直到子執行緒死亡,notifyAll()方法將被呼叫,喚醒等待的執行緒。
public final synchronized void join(long millis) throws InterruptedException { long base = System.currentTimeMillis(); long now = 0; if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (millis == 0) { while (isAlive()) {//如果子執行緒還活著,則一直迴圈 wait(0);//主執行緒進入阻塞 } } else { while (isAlive()) { long delay = millis - now; if (delay <= 0) { break; } wait(delay); now = System.currentTimeMillis() - base; } } }