Thread中,join()方法的作用是調用線程等待該線程完成后,才能繼續用下運行。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public class TestThread5 { public static void main(String[] args) throws InterruptedException { Runner0 run5 = new Runner0(); Thread th5 = new Thread(run5); th5.start(); th5.join();//join()方法用在此處是為了等待主線程結束后運行子線程 for(int i=0;i<5;i++){ System.out.println("子線程:"+i); } } } class Runner0 implements Runnable{ public void run(){ for(int i=0;i<5;i++) System.out.println("主線程:"+i); } } |
上述代碼的運行結構如下所示:
當然,如果不使用join()方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public class TestThread6{ public static void main(String[] args) throws InterruptedException { Runner0 run5 = new Runner0(); Thread th5 = new Thread(run5); th5.start(); // th5.join(); for(int i=0;i<4;i++){ System.out.println("子線程:"+i); } } } class Runner0 implements Runnable{ public void run(){ for(int i=0;i<4;i++) System.out.println("主線程:"+i); } } |
如上代碼注釋掉jion()方法,
根據上面兩個不同的代碼,輸出的不同,很容易就能理解join()方法。
以上這篇基于多線程中join()的用法實例講解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/xiangpeng/p/7656780.html