A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
案例(来自源码注释)
import java.util.concurrent.CountDownLatch;
public class Driver {
private final static int N =10;
public static void main(String[] args)throws Exception {
CountDownLatch startSignal =new CountDownLatch(1);
CountDownLatch doneSignal =new CountDownLatch(N);
for (int i =0; i
new Thread(new Worker(startSignal, doneSignal)).start();
}
startSignal.countDown();// let all threads proceed
System.out.println("-----比赛开始--------");
doneSignal.await();// wait for all to finish
System.out.println("均已到终点,比赛结束");
}
static class Workerimplements Runnable {
final CountDownLatchstartSignal;
final CountDownLatchdoneSignal;
public Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
this.startSignal = startSignal;
this.doneSignal = doneSignal;
}
@Override
public void run() {
try {
startSignal.await();
System.out.println(Thread.currentThread().getName() +"加速,冲刺");
System.out.println(Thread.currentThread().getName() +"到终点");
doneSignal.countDown();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
网友评论