在网上看到一个例子
public class JoinTester01 implements Runnable { private String name; public JoinTester01(String name) { this.name = name; } public void run() { System.out.printf("%s begins: %s ", name, new Date()); try { TimeUnit.SECONDS.sleep(4); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("%s has finished: %s ", name, new Date()); } public static void main(String[] args) { Thread thread1 = new Thread(new JoinTester01("One")); Thread thread2 = new Thread(new JoinTester01("Two")); thread1.start(); thread2.start(); /*try { thread1.join(); thread2.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ System.out.println("Main thread is finished"); } }
输出结果是
Main thread is finished
OneWed Mar 01 09:04:52 UTC 2017
TwoWed Mar 01 09:04:52 UTC 2017
TwoWed Mar 01 09:04:52 UTC 2017
OneWed Mar 01 09:04:52 UTC 2017
开始不相信为什么main()的主线程都完成了,子线程还能执行,自己试了一下发现真的是这样。
原来,主线程是一个非守护线程,所以主线程执行完了并不影响其他子线程,其他子线程依然该怎么运行就还怎么运行。主线程和子线程优先级一样但是主线程会先抢占CPU,先执行。所以就会出现这样的结果。
如果加上join代码部分,结果就会使真阳:
TwoWed Mar 01 09:10:39 UTC 2017
OneWed Mar 01 09:10:39 UTC 2017
TwoWed Mar 01 09:10:40 UTC 2017
OneWed Mar 01 09:10:40 UTC 2017
Main thread is finished
thread1.join()的意思就相当于从现在开始,thread1这个线程就接在main()线程后面执行了,只有执行完thread1线程之后才会继续主线程。