博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java 提升之CountDownLatch
阅读量:5846 次
发布时间:2019-06-18

本文共 2595 字,大约阅读时间需要 8 分钟。

CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。

主要方法

 public CountDownLatch(int count);

 public void countDown();

 public void await() throws 

 

构造方法参数指定了计数的次数

countDown方法,当前线程调用此方法,则计数减一

awaint方法,调用此方法会一直阻塞当前线程,直到计时器的值为0

package com.study.thread.concurrent;import java.util.Random;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * @author draem0507 * @TODO 学下countdownLatch * @version 0.1 * @create 2012 15:03:28 *  */public class CountDownLatchTest {    /**     * 

* CountDownLatch类是一个同步计数器,构造时传入int参数, *

*

* 该参数就是计数器的初始值,每调用一次countDown()方法,计数器减1, *

*

* 计数器大于0 时,await()方法会阻塞程序继续执行 *

*/ public static void main(String[] args) { CountDownLatch countDownLatch = new CountDownLatch(3); Worker worker1 = new Worker("小明", countDownLatch); Worker worker2 = new Worker("小红", countDownLatch); Worker worker3 = new Worker("小强", countDownLatch); Boss boss = new Boss(countDownLatch); ExecutorService service = Executors.newCachedThreadPool(); service.execute(worker1); service.execute(worker2); service.execute(worker3); service.execute(boss); service.shutdown(); }}class Worker implements Runnable { private String name; private CountDownLatch countDownLatch; public void run() { doWork(); try { Thread.sleep((new Random().nextInt(10)) * 1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(name + "-->结束干活"); countDownLatch.countDown(); } public Worker(String name, CountDownLatch countDownLatch) { this.name = name; this.countDownLatch = countDownLatch; } private void doWork() { System.out.println(name + "-->正在干活"); }}class Boss implements Runnable { private CountDownLatch countDownLatch; public Boss(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; } public void run() { System.out.println("老板正在等待验工"); try { countDownLatch.await(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("工人干活都结束,老板开始验工"); }}

结果:

小明-->正在干活小红-->正在干活老板正在等待验工小强-->正在干活小强-->结束干活小明-->结束干活小红-->结束干活工人干活都结束,老板开始验工

不一定都按上述结果呈现,但是最后一句话肯定是最后执行

参考:

  

  http://www.iteye.com/topic/1002652

转载于:https://www.cnblogs.com/draem0507/archive/2012/12/24/2831072.html

你可能感兴趣的文章
UITableview中cell重用引起的内容重复的问题
查看>>
stm32 ADC使用 单通道 多通道
查看>>
Windows服务器配置与管理
查看>>
UVA 10003 Cutting Sticks
查看>>
DRP项目总结
查看>>
图的连通性——无向图的连通分量和生成树
查看>>
Linux安装更新JDK
查看>>
VM10.0上创建Windows server 2008 SP2,并且,安装loadrunner11
查看>>
抽象工厂
查看>>
linux下高可用mysql
查看>>
(15)Reactor 3 Operators——响应式Spring的道法术器
查看>>
r710 网卡驱动升级灰常蛋疼,现在在祈祷
查看>>
Microsoft Internet Explorer 数字错误漏洞
查看>>
添加 修改 删除
查看>>
RabbitMQ的远程Web管理与监控工具
查看>>
Linux术语全称
查看>>
Weave and Docker for Mac: The bridge between local and remote services
查看>>
MacOS Sierra安装nodejs
查看>>
ln -s 软链接应用-磁盘空间不够用的解决方案
查看>>
Windows7操作系统安装教程(图文)
查看>>