首页 > 代码库 > 指定线程执行的顺序---join()

指定线程执行的顺序---join()

线程T1,T2,T3分别启动,如何让其执行顺序变为T3>T2>T1:

线程1:

 1 package test6;
 2 
 3 public class Thread1 extends Thread{
 4 
 5     private Thread thread2;
 6     public Thread1(Thread thread2){
 7         this.thread2=thread2;
 8     }
 9     @Override
10     public void run(){
11         try {
12             thread2.join();
13             System.out.println("线程1在执行");
14         } catch (InterruptedException e) {
15             e.printStackTrace();
16         }
17     }
18 }

线程2:

 1 package test6;
 2 
 3 public class Thread2 extends Thread{
 4 
 5     private Thread thread3;
 6     public Thread2(Thread thread3){
 7         this.thread3=thread3;
 8     }
 9     @Override
10     public void run(){
11         try {
12             thread3.join();
13             System.out.println("线程2在执行");
14         } catch (InterruptedException e) {
15             e.printStackTrace();
16         }
17     }
18 }

线程3:

 1 package test6;
 2 
 3 public class Thread3 extends Thread{
 4 
 5     @Override
 6     public void run(){
 7         try {
 8             System.out.println("线程3在执行。。。");
 9             Thread.sleep(2000);
10         } catch (InterruptedException e) {
11             // TODO Auto-generated catch block
12             e.printStackTrace();
13         }
14     }
15 }

执行:

 1 package test6;
 2 
 3 public class Run {
 4 
 5     public static void main(String[] args) {
 6         Thread3 t3=new Thread3();
 7         Thread2 t2=new Thread2(t3);
 8         Thread1 t1=new Thread1(t2);
 9         t1.start();
10         t2.start();
11         t3.start();
12     }
13 }

如图:启动顺序为t1,t2,t3.但是使用join后,执行顺序为t3,t2,t1

join的作用:使当前线程等正在执行的线程执行完。join内部调用的是wait方法没,所以释放锁。sleep不释放锁。

 

指定线程执行的顺序---join()