/**
* (1)
* 所有的运动员都等待裁判发布命令
* (2)
* 裁判等待运动员的到达
*/
public class CountDownLatchTest {
public static void main(String[] args){
ExecutorService threadPool = Executors.newCachedThreadPool();
final CountDownLatch cdOrder= new CountDownLatch(1);
final CountDownLatch cdAnswer = new CountDownLatch(3);
for(int i=0;i<3;i++){
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
System.out.println("线程"+Thread.currentThread().getName()+"正准备接受命令");
cdOrder.await();
System.out.println("线程"+Thread.currentThread().getName()+"已经接受命令");
Thread.sleep((long)(Math.random()*10000));
System.out.println("线程"+Thread.currentThread().getName()+"回应命令处理结果");
cdAnswer.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
threadPool.execute(runnable);
}
try {
Thread.sleep((long)(Math.random()*10000));
System.out.println("线程"+Thread.currentThread().getName()+"即将发布命令");
cdOrder.countDown();
System.out.println("线程"+Thread.currentThread().getName()+"已经发布命令,正在等待结果");
cdAnswer.await();
System.out.println("线程"+Thread.currentThread().getName()+"已经收到,所有的响应的结果");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
如有疑问,请发邮件:1176306419@qq.com
github:??https://github.com/wangrui0/