标签:long ble 倒计时 service 计时器 对象 作者 stack log
/** * * @描述: 倒计时器 . * 犹如倒计时计数器,调用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
标签:long ble 倒计时 service 计时器 对象 作者 stack log
原文地址:http://www.cnblogs.com/superGG/p/6902419.html