咱們先看一個例子,在這個例子中你會發現主線程結束後,過了一段時間兩個子線程才結束。java
定義實現Runnable接口的線程類,模擬執行必定時間後結束。dom
public class MyRunnable implements Runnable{ @Override public void run() { System.out.printf("%s: I am start working.\n", Thread.currentThread().getName()); try { TimeUnit.SECONDS.sleep((long) (Math.random() * 10 + 1)); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("%s: I am end working.\n", Thread.currentThread().getName()); } }
定義主方法,啓動兩個子線程:ide
public class Main { public static void main(String[] args) { Thread thread1 = new Thread(new MyRunnable()); Thread thread2 = new Thread(new MyRunnable()); System.out.printf("%s: start two threads.\n", Thread.currentThread().getName()); thread1.start(); thread2.start(); System.out.printf("%s: end.\n", Thread.currentThread().getName()); } }
查看控制檯日誌,你會發現主線程先於兩個子線程而結束。線程
main: start two threads. main: end. Thread-1: I am start working. Thread-0: I am start working. Thread-1: I am end working. Thread-0: I am end working.
當你想讓主線程等待全部子線程執行結束後,再執行一段代碼才結束,應該怎麼作呢。Java提供了join()方法。咱們重寫主方法,在主方法中調用子線程的join()方法,便可讓主線程進入WAITING狀態並等待子線程終止後繼續執行。日誌
public class Main { public static void main(String[] args) { Thread thread1 = new Thread(new MyRunnable()); Thread thread2 = new Thread(new MyRunnable()); System.out.printf("%s: start two threads.\n", Thread.currentThread().getName()); thread1.start(); thread2.start(); try { thread2.join(); thread1.join(); System.out.printf("%s: child runnable both ends.\n", Thread.currentThread().getName()); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("%s: end.\n", Thread.currentThread().getName()); } }
查看控制檯日誌,你會發現主線程在等待兩個子線程終止以後才繼續執行。code
main: start two threads. Thread-0: I am start working. Thread-1: I am start working. Thread-0: I am end working. Thread-1: I am end working. main: child runnable both ends. main: end.