调用thread.join() 方法必须等thread 执行完毕,当前线程才能继续往下执行,而CountDownLatch通过计数器提供了更灵活的控制,只要检测到计数器为0当前线程就可以往下执行而不用管相应的thread是否执行完毕。
例子:
package com;
import java.util.concurrent.CountDownLatch;public class Worker extends Thread {
//工作者
private String name;
//第一阶段工作时间
private long time;
private CountDownLatch countDownLatch;
public Worker(String name, long time,CountDownLatch countDownLatch) {
super();
this.name = name;
this.time = time;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
try {
System.out.println(name+"开始工作");
Thread.sleep(time);
System.out.println(name+"第一阶段工作完成,消耗时间time="+time);
countDownLatch.countDown();
Thread.sleep(10000);
System.out.println(name+"第二阶段工作完成,消耗时间time="+(time+10000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(2);
Worker worker0 = new Worker("worker0", (long)(Math.random()*2000+3000),countDownLatch);
Worker worker1 = new Worker("worker1", (long)(Math.random()*2000+3000),countDownLatch);
Worker worker2 = new Worker("worker2", (long)(Math.random()*2000+3000),countDownLatch);
worker0.start();
worker1.start();
countDownLatch.await();
System.out.println("准备工作继续");
worker2.start();
}
}