java计数器CountDownLatch
Posted 风的低吟
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java计数器CountDownLatch相关的知识,希望对你有一定的参考价值。
CountDownLatch里面有个属性为state,当为零时触发代码往下执行,代码如下:
package threadLock; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CountDownLatchTest { public static void main(String[] args) { final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(3); ExecutorService service = Executors.newCachedThreadPool(); for (int i = 0; i < 3; i++) { service.execute(new Runnable() { @Override public void run() { try { System.out.println("线程" + Thread.currentThread().getName() + "正在等待命令。"); latch1.await(); System.out.println("线程" + Thread.currentThread().getName() + "正在处理。"); Thread.sleep(new Random().nextInt(1000)); latch2.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }); } try { Thread.sleep(1000); System.out.println("thread main 发布命令。"); System.out.println("thread main 正在收集各线程响应。"); latch1.countDown(); latch2.await(); System.out.println("thread main已收集所有线程的响应。"); } catch (InterruptedException e) { e.printStackTrace(); } } }
以上是关于java计数器CountDownLatch的主要内容,如果未能解决你的问题,请参考以下文章
Java多线程-两种常用的线程计数器CountDownLatch和循环屏障CyclicBarrier