本文主要是介绍多线程和并发库应用十五-CountDownLatch,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
CountDownLatch类位于java.util.concurrent包下,利用它可以实现类似计数器的功能,当计数为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.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();}
}
文章地址:http://www.haha174.top/article/details/255964
项目源码:https://github.com/haha174/thread-learning.git
这篇关于多线程和并发库应用十五-CountDownLatch的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!