现在的位置: 首页 > 综合 > 正文

java线程系列—同步器之CountDownLatch

2018年04月12日 ⁄ 综合 ⁄ 共 1146字 ⁄ 字号 评论关闭

 CountDownLatch 是一个极其简单但又极其常用的实用工具,用于在保持给定数目的信号、事件或条件前阻塞执行,通过调用await(),countDown()方法,实现同步功能。

例子:有三个线程,等待主线程下发命令,当主线程下发命令时,三个线程会接收命令,并执行,主线程接收执行完的结果

public class CountdownLatchTest {

public static void main(String[] args) {
ExecutorService service = 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(){
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 (Exception e) {
e.printStackTrace();
}
}
};
service.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 (Exception e) {
e.printStackTrace();
}
service.shutdown();
}
}


抱歉!评论已关闭.