线程加入

线程加入:暂停此线程,执行另外一个线程。

线程对象B.join()   无参数,则A线程一直暂停,直到B线程运行结束。

线程对象B.join(时间t)   有参数,则A线程每隔t时间暂停一次,直到B线程运行结束。

例子:

 1 public class ThreadJoin {
 2 
 3     public static void main(String[] args) {
 4         // TODO Auto-generated method stub
 5         Thread t1 =new Thread(){
 6             public void run(){
 7                 for(int i=0; i<10; i++)
 8                     System.out.println("a");
 9             }
10         };
11         Thread t2 =new Thread(){
12             public void run(){
13                 for(int i=0; i<10; i++){
14                     if(i == 2){
15                         try {
16                             t1.join();//t1加入
17                         } catch (InterruptedException e) {
18                             // TODO Auto-generated catch block
19                             e.printStackTrace();
20                         }
21                     }
22                     System.out.println("bbb");
23                 }
24                     
25             }
26         };
27 
28         t2.start();
29         t1.start();
30     }
31 
32 }

结果:

 1 bbb
 2 bbb
 3 a
 4 a
 5 a
 6 a
 7 a
 8 a
 9 a
10 a
11 a
12 a
13 bbb
14 bbb
15 bbb
16 bbb
17 bbb
18 bbb
19 bbb
20 bbb
原文地址:https://www.cnblogs.com/feichangnice/p/10648855.html