等待該線程終止,好比A線程調用了B線程的join,那麼A線程要等到B線程執行完後,才能夠繼續執行。ide
public class JoinDemo { static class JoinThread1 implements Runnable { Thread thread; public JoinThread1(Thread thread) { this.thread = thread; } @Override public void run() { System.out.println("thread1 start"); try { thread.join(); System.out.println("thread1 end"); } catch (InterruptedException e) { e.printStackTrace(); } } } static class JoinThread2 implements Runnable { @Override public void run() { System.out.println("thread2 start"); try { Thread.sleep(10000); System.out.println("thread2 end"); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { JoinThread2 joinThread2 = new JoinThread2(); Thread thread2 = new Thread(joinThread2); JoinThread1 joinThread1 = new JoinThread1(thread2); Thread thread1 = new Thread(joinThread1); thread1.start(); thread2.start(); } }
運行結果以下:
線程1執行的時候,調用線程2的join,線程1不休眠,線程2休眠了10秒,從結果看出來,線程2執行完後,線程1才執行完。this