多线程之计数器CountDownLatch来控制线程的顺序

/**
 * 线程等待,类似线程join的作用
 * 假设3个线程:2个T1与1个T2, T1执行完之后, T2再执行
 * 除了可以使用join控制线程的执行顺序,还可以使用CountDownLatch控制线程的先后顺序
 */
public class CountDownLatchTest {
 private AtomicInteger total;
 CountDownLatch latch = new CountDownLatch(2);

 public static void main(String[] args) {
  CountDownLatchTest o = new CountDownLatchTest();
  T1 t1 = o.new T1("t1");
  T1 t2 = o.new T1("t2");
  T2 t3 = o.new T2("t3");
  
  t1.start();
  t3.start();
  t2.start();
 }

 class T1 extends Thread{
  public T1(String name) {
   super(name);
  }
  
  public void run() {
   System.out.println(this.getName() + "  " + System.currentTimeMillis());
   try {
    Thread.sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   latch.countDown();
  }
 }
 
  class T2 extends Thread{
  public T2(String name) {
   super(name);
  }
  
  public void run() {
   try {
    latch.await(); //等待2个T1线程执行完(阻塞直到计数为0)
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   System.out.println(this.getName() + "  " + System.currentTimeMillis());
  }
 }
}

猜你喜欢

转载自zw7534313.iteye.com/blog/2419678