使用join让线程按顺序执行

阅读更多

 

//使用join三个线程按顺序执行: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());
  }
 }
}

你可能感兴趣的:(多线程)