Use join to make threads execute sequentially

 

//Use join to execute three threads in order: T1, T2, T3
public class Test {
 T1 t1;
 T2 t2;
 T3 t3;
 
 public Test() {
  t1 = new T1("t1");
  t2 = new T2(" t2");
  t3 = new T3("t3");
  t1.start();
  t2.start();
  t3.start();
 }

 public static void main(String[] args) {
  Test obj = new Test();
 }
 
 class T1 extends Thread{
  
  public T1(String name) {
   super(name);
  }
  
  public void run() {
   long i = 100*60*60*128;
   System.out.println(this.getName() + " " + System.nanoTime());
  }
 }
 
    class T2 extends Thread{
  
  public T2(String name) {
   super(name);
  }
  
  public void run() {
   try {
    t1.join(); //等待t1线程结束
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   System.out.println(this.getName() + " " + System.nanoTime());
  }
 }

    class T3 extends Thread{
 
  public T3(String name) {
   super(name);
  }
  
  public void run() {
   try {
    t2.join(); //等待t2线程结束
    Thread.sleep(500);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   System.out.println(this.getName() + " " + System.nanoTime());
  }
 }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326048651&siteId=291194637