参考:http://www.ibm.com/developerworks/cn/java/j-5things5.html

【关于 java.util.concurrent 您不知道的 5 件事,第 2 部分】

1,Semaphore

适用于:限制未处理的特定资源请求(线程/操作)数量。

public class SemApp {public static void main(String[] args) {Runnable limitedCall = new Runnable() {final Random rand = new Random();final Semaphore available = new Semaphore(3);int count = 0;public void run() {int time = rand.nextInt(15);int num = count++;try {available.acquire();System.out.println("Executing " + "long-running action for " + time + " seconds... #" + num);Thread.sleep(time * 1000);System.out.println("Done with #" + num + "!");available.release();} catch (InterruptedException intEx) {intEx.printStackTrace();}}};for (int i=0; i<10; i++)new Thread(limitedCall).start();}
}

程序中实现了,限制了同时打开的任务数是三个。

结果 写道
Executing long-running action for 9 seconds... #0
Executing long-running action for 7 seconds... #2
Executing long-running action for 0 seconds... #1
Done with #1!
Executing long-running action for 1 seconds... #3
Done with #3!
Executing long-running action for 6 seconds... #4
Done with #2!
Executing long-running action for 5 seconds... #5
Done with #4!
Executing long-running action for 6 seconds... #6
Done with #0!
Executing long-running action for 12 seconds... #7
Done with #5!
Executing long-running action for 1 seconds... #8
Done with #8!
Executing long-running action for 12 seconds... #9
Done with #6!
Done with #7!
Done with #9!

对于特定资源和线程访问数的限定Semaphore是个不错的选择。这里使用了Semaphore一次使用和释放一个通行证,Semaphore还可以一次使用和释放多个通行证。

2,CountDownLatch

public class CDLApp {public static void main(String[] args)throws InterruptedException, java.io.IOException {System.out.println("Prepping...");Race r = new Race("horse 1", "horse 2",    "horse 3",    "horse 4","horse 5",    "horse 6",    "horse 7",    "horse 8");System.out.println("It's a race of " + r.getDistance() + " lengths");System.out.println("Press Enter to run the race....");System.in.read();r.run();}
}
class Race {private Random rand = new Random();private int distance = rand.nextInt(250);private List<String> horses = new ArrayList<String>();public Race(String... names) {this.horses.addAll(Arrays.asList(names));}public int getDistance() {return distance;}public void run() throws InterruptedException {System.out.println("And the horses are stepping up to the gate...");final CountDownLatch start = new CountDownLatch(1);final CountDownLatch finish = new CountDownLatch(horses.size());final List<String> places =Collections.synchronizedList(new ArrayList<String>());for (final String h : horses) {new Thread(new Runnable() {public void run() {try    {start.await();//等待赛马开始System.out.println(h + " stepping up to the gate...");int traveled = 0;while (traveled < distance)    {//前进一次 暂停 0-2 秒Thread.sleep(rand.nextInt(3) * 1000);//前进 0-14 米traveled += rand.nextInt(15);System.out.println(h + " advanced to " + traveled + "!");}System.out.println(h + " crossed the finish!");places.add(h);finish.countDown();//一个马到达终点就 减去一, 倒数完成比赛结束}catch (InterruptedException intEx) {System.out.println("ABORTING RACE!!!");intEx.printStackTrace();}}}).start();}System.out.println("And... they're off!");start.countDown();//开始赛马finish.await();//等待所有的马跑完System.out.println("============================================");System.out.println("And we have our winners!");System.out.println("<"+places.get(0)+">" + " took the gold...");System.out.println("<"+places.get(1)+">" + " got the silver...");System.out.println("and " + "<"+places.get(2)+">" + " took home the bronze.");System.out.println("============================================");}
}

上面的程序利用CountDownLatch 描述一个赛马的过程,首先让所有马在门闩那里(start.countDown();//开始赛马)等待开始,每匹马冲过终点后(finish.countDown),finish.await()等待所有的马冲过终点后,发奖牌。

3,ScheduledExecutorService

public class Ping {public static void main(String[] args) {ScheduledExecutorService ses =Executors.newScheduledThreadPool(1);Runnable pinger = new Runnable() {public void run() {System.out.println("PING!");}};ses.scheduleAtFixedRate(pinger, 1, 2, TimeUnit.SECONDS);}
}

模拟心脏每隔2秒钟跳动一次。顺便说一下,如果用户希望取消心跳,scheduleAtFixedRate 调用将返回一个 ScheduledFuture 实例,它不仅封装了结果(如果有),还拥有一个 cancel 方法来关闭计划的操作。

java多线程 Semaphore CountDownLatch ScheduledExecutorService相关推荐

  1. Java多线程:Semaphore

    自从5.0开始,jdk在java.util.concurrent包里提供了Semaphore 的官方实现. Java 5.0里新加了4个协调线程间进程的同步装置,它们分别是: Semaphore, C ...

  2. Java多线程-Semaphore(限流)

    Semaphore 是什么 Semaphore 通常我们叫它信号量, 可以用来控制同时访问特定资源的线程数量,通过协调各个线程,以保证合理的使用资源. 可以把它简单的理解成我们停车场入口立着的那个显示 ...

  3. java多线程中CountDownLatch和join的使用

    在工作中,我们经常需要和多线程打交道,简单说明一个场景,在工厂流水线上有2条流水线,流水线同时开工生产零件,但是每个零件生产时间不一样,只有等到两个零件都生产完毕之后才能开始总组装.那我们很快想到jo ...

  4. Java多线程协作CountDownLatch,主线程等待子线程结束

    CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待. 主要方法 public CountDownLatch(int count);构造方 ...

  5. Java多线程-通讯方式

    Java多线程-通讯方式 线程之间为什么要通信? 通信的目的是为了更好的协作,线程无论是交替式执行,还是接力式执行,都需要进行通信告知.那么java线程是如何通信的呢,大致有以下六种方式. Java线 ...

  6. Java多线程(八)之Semaphore、CountDownLatch、CyclicBarrier、Exchanger

    一.引言 Semaphore               :一个计数信号量 CountDownLatch          :一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线 ...

  7. Java多线程系列(九):CountDownLatch、Semaphore等4大并发工具类详解

    之前谈过高并发编程系列:4种常用Java线程锁的特点,性能比较.使用场景 ,以及高并发编程系列:ConcurrentHashMap的实现原理(JDK1.7和JDK1.8) 今天主要介绍concurre ...

  8. Android 价值千万java多线程同步 lt;五CountDownLatch(计数器)和Semaphore(信号量)

    1).Android 价值千万   java线程专题:Wait&notify&join&Yield http://blog.csdn.net/whb20081815/artic ...

  9. JAVA多线程信号量Semaphore

    1.Semaphore 是什么 Semaphore 通常我们叫它信号量, 可以用来控制同时访问特定资源的线程数量,通过协调各个线程,以保证合理的使用资源. 可以把它简单的理解成我们停车场入口立着的那个 ...

  10. JAVA多线程-CountDownLatch计数器

    一.概述 CountDownLatch是一个同步工具类,它允许一个或多个线程等待其他线程执行完操作之后再继续执行.通常用于控制多个线程的执行顺序. 二.基本原理 我们可以把CountDownLatch ...

最新文章

  1. playsound函数Linux使用,函数PlaySound和sndPlaySound的用法
  2. eclipse中一个项目引用另一个项目的方法
  3. 图像编解码:CRF(质量/码率控制)和QP
  4. java中文乱码 寮犱笁_MySQL命令窗口中文乱码或插入中文数据失败
  5. 【机器学习】自己手写实现线性回归,梯度下降 原理
  6. Leetcode——两数之和
  7. 可视化+数据+图表,报告规范这么写才能升职
  8. bzoj 3895: 取石子(博弈)
  9. zendstudio的安装与配置
  10. GX Works2使用问题记录
  11. HTML前端代码分析(查看网站黑链的几种方法)暗链是什么意思
  12. pb语言是什么计算机语言,pb编程语言排行榜_世界编程语言排行榜 搜狗百科
  13. 利用一种新的灵活记分卡方法改进肽抗癌活性的预测和表征
  14. c语言编程新思路知道答案,C语言编程新思路知道答案公众号
  15. web浏览器上画图之raphael
  16. 2188 完成比赛的最少时间(递推)
  17. [NodeJS实战][Vue实战]Vue-PixiJS [开箱可用][新手极简]
  18. 2022-2028全球与中国激光显示技术市场现状及未来发展趋势
  19. 克林顿的竞选活动:机器学习和Java是否可以防止它们无法处理大数据?
  20. c# linq goup by实例

热门文章

  1. poi导出xlsx文件后,打开报“因为文件格式或文件扩展名无效。请确定文件未损坏,并且文件扩展名与文件的格式匹配。”的解决方法
  2. 微信跳一跳小游戏使用charles抓包工具改分攻略
  3. yum安装软件报错:Invalid configuration value: failovermethod=priority...
  4. 2022图片在线加水印源码
  5. [并发并行]_[pthread]_[使用线程池并发复制文件]
  6. 哪一类功率放大电路效率最高_让我们来复习一下功率放大电路与集成运算放大电路...
  7. vue 上传图片进行压缩图片
  8. ORACLE表空间碎片整理
  9. 如何修改路由器dns服务器,怎么修改路由器DNS地址
  10. 常用的前端框架有哪些?