CountDownLatch, 允许一组线程都完成后再执行某些事情,
例如A 线程需要等待 B C D线程 都执行完成后再执行
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(2);
new Thread(new Manager(latch)).start();
Thread.sleep(2000);
new Thread(new Manager(latch)).start();
Thread.sleep(10000);
new Thread(new Work(latch)).start();
new Thread(new Work(latch)).start();
System.out.println("main thread");
}
class Work implements Runnable {
private CountDownLatch latch;
public Work(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
Thread.sleep(5000);
System.out.println("我完成了");
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Manager implements Runnable {
private CountDownLatch latch;
public Manager(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
latch.await();
System.out.println("你们完成了,我要开始工作了");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果:
main thread
我完成了
我完成了
你们完成了,我要开始工作了