并发包java.util.concurrent.CountDownLatch
Posted 安静
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了并发包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的主要内容,如果未能解决你的问题,请参考以下文章