java使用CountDownLatch实现线程顺序执行

package concurrent;


import java.util.concurrent.CountDownLatch;


public class ThreadSequence {


   public static void main(String[] args) throws InterruptedException {
       final CountDownLatch latch1 = new CountDownLatch(1);
       Thread t1 = new Thread(new FirstThread(latch1));
       final CountDownLatch latch2 = new CountDownLatch(1);
       Thread t2 = new Thread(new SecondThread(latch2));
       final CountDownLatch latch3 = new CountDownLatch(1);
       Thread t3 = new Thread(new ThirdThread(latch3));
       
       t1.start();
       latch1.await();
       t2.start();
       latch2.await();
       t3.start();
       latch3.await();
       System.out.println("the main thread is End...");
   }
}

class FirstThread implements Runnable{

  private final CountDownLatch latch;


   public FirstThread(CountDownLatch latch) {
       this.latch = latch;
   }


   public void run() {
       System.out.println("the first thread is running!");
   
       
       SleepUtils.sleep(5);
       System.out.println("FirstThread----------->count=" + latch.getCount());
       latch.countDown();
   }
}

class SecondThread implements Runnable{

  private final CountDownLatch latch;


   public SecondThread(CountDownLatch latch) {
       this.latch = latch;
   }
   public void run() {
       System.out.println("the second thread is running!");
       
       SleepUtils.sleep(2);
       System.out.println("SecondThread----------->count=" + latch.getCount());
       latch.countDown();
   }
}
class ThirdThread implements Runnable{

  private final CountDownLatch latch;


   public ThirdThread(CountDownLatch latch) {
       this.latch = latch;
   }


   public void run() {
       System.out.println("the third thread is running!");
    
       System.out.println("ThirdThread----------->count=" + latch.getCount());
       latch.countDown();
   }
}

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