今天又把join的用法大概看了一下,其實理解起來,還是比較簡單。用個簡單的例子說明一下吧。
1、通過下面的例子,可以看到說出結果中首先全部是是Thread-1,之后才會是Thread-2,這是因為在主線程中調用了thread1的join方法,就等於將主線程和thread1的執行方式由並行改為了串行,也就是必須當thread1全部執行結束之后,才會調用thread2的方法。這就可以解釋為啥先全部是thread-1之后才會有thread-2了。
public class TestJoin { public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(new JoinThread());; Thread thread2 = new Thread(new JoinThread()); thread1.start(); thread1.join(); thread2.start(); } static class JoinThread implements Runnable { @Override public void run() { for(int i=0; i<100; i++) { try { System.out.println(Thread.currentThread().getName()); Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
2、關於join方法其實還可以提交過期時間,也就是在執行到達預定時間后,執行方式將繼續以並行的方式執行。
thread1.join(10);//表示10ms后,將結束join。
3、通過join的源碼中可以到,其實join的本質還是調用的wait方法。關於wait方法的實現,就無法分析了。因為它是個native方法,無法進一步查看源碼了
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; } } }
