首页 > 代码库 > 并发包java.util.concurrent.CountDownLatch
并发包java.util.concurrent.CountDownLatch
/** * * @描述: 倒计时器 . * 犹如倒计时计数器,调用CountDownLatch对象的countDown方法就将计数器减1,当计算器为0的时候 * 则所有等待者或单个等待者开始执行 * @作者: Wnj . * @创建时间: 2017年5月15日 . * @版本: 1.0 . */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=1所有线程进入等待,上面的out会打印 cdOrder.await(); System.out.println("线程" + Thread.currentThread().getName() + "已接受命令"); Thread.sleep((long)(Math.random() * 10000)); System.out.println("线程" + Thread.currentThread().getName() + "回应命令处理结果"); //cdAnswer=3 cdAnswer.countDown(); } catch (Exception e) { e.printStackTrace(); } } }; service.execute(runnable); } //主线程 try { Thread.sleep((long)(Math.random() * 10000)); System.out.println("线程" + Thread.currentThread().getName() + "即将发布命令"); ////cdOrder=1 将cdOrder减1 = 0 cdOrder.countDown(); System.out.println("线程" + Thread.currentThread().getName() + "已发送命令,正在等待结果"); //cdAnswer= 3 cdAnser进入等待 cdAnswer.await(); System.out.println("线程" + Thread.currentThread().getName() + "已收到所有响应结果"); } catch (Exception e) { e.printStackTrace(); } service.shutdown(); }}
并发包java.util.concurrent.CountDownLatch
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。