join方法的作用
thread.join()方法用於把指定的線程加入到當前線程中,把當前線程的CPU執行時間讓給另一個線程。比如在線程B中調用了線程A的Join()方法,直到線程A執行完畢后,才會繼續執行線程B。
threadA.join(); //把當前線程執行時間讓給threadA線程,直到threadA執行完畢才會繼續執行當前線程
threadA.join(1000); //把當前線程執行時間讓給threadA線程,1000毫秒后,A、B兩個線程再重新競爭
join方法的源碼如下,可以看出是通過while和wait的方式進行控制:
/** * Waits at most <code>millis</code> milliseconds for this thread to * die. A timeout of <code>0</code> means to wait forever. */ //此處A timeout of 0 means to wait forever 字面意思是永遠等待,其實是等到t結束后。 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; } } }
下面這個程序的輸出結果是多少?A:0 B:1000 C:1 D:不確定
public class ThreadTest extends Thread { public static int a = 0; public void run() { for (int k = 0; k < 100000; k++) { a = a + 1; } } public static void main(String[] args) throws Exception { Thread t = new ThreadTest(); t.start(); t.join(1); System.out.println(a); } }
答案是:D。因為t.start()只是讓線程進入了RUNNABLE狀態,但並不一定在1毫秒內執行到t線程的run方法。如果沒有走進t線程的run方法,直接執行了主線程的打印語句,則輸出結果為0;如果進入了t線程的run方法,並且在1毫秒內將t線程的run方法執行完畢,則輸出結果為100000;否則,可能是0~100000之間的任意數字。因此最終答案不能確定