java多线程 等待多个并发事件的完成
来源:互联网 发布:网络直播主持稿 编辑:程序博客网 时间:2024/05/29 07:05
java API中提供了CountDownLatch类,它允许线程一直等待,知道等待操作结束。下面以一个视频会议等待人数为例。
1.视频会议类,实现Runnable接口。
import java.util.concurrent.CountDownLatch;public class Videoconference implements Runnable { private final CountDownLatch controller; public Videoconference(int number){ controller = new CountDownLatch(number); } //每一个视频会议者到达是都执行此方法 public void arrive(String name){ System.out.printf("%s has arrived.",name); controller.countDown(); //还没有到达的人数 System.out.printf("Videoconferencr has waitinf for %d participants\n",controller.getCount()); } public void run() { System.out.printf("Videoconference initialization:%d participants.\n",controller.getCount()); try { //等待所有人到达,如果没有这句,则会在参与人没到达之前开始会议 controller.await(); System.out.printf("Videoconference:ALL participants has come\n"); System.out.print("Videoconference:Let is start...\n"); } catch (InterruptedException e) { e.printStackTrace(); } }}
2.与会者类
import java.util.concurrent.TimeUnit;public class Participant implements Runnable{private Videoconference conference;public String name;public Participant(Videoconference conference,String name){ this.conference = conference; this.name = name;}@Overridepublic void run() { long duration = (long)(Math.random()*10); try { TimeUnit.SECONDS.sleep(duration); } catch (InterruptedException e) { e.printStackTrace(); } conference.arrive(name);}}
3.主方法
package Thread03semaphone;public class Main2 {public static void main(String[] args){ Videoconference videoConference = new Videoconference(10); Thread threadconference = new Thread(videoConference); threadconference.start(); for(int i =0;i<10;i++){ Participant p = new Participant(videoConference,"Participant"+i); Thread t = new Thread(p); t.start(); }}}
当创建CountDownLatch对象时,通过构造器来初始化内部计数器(本例中为10),当countdown()方法被调用时,计数器将减1,当计数器为0时,countdownlatch将唤醒所有等待的线程。
注意点:
- CountDownLatch对象计数器一旦被初始化之后,就不可以修改。
- 他并不是用来保护临界资源或者同步代码块,只是用来同步多个任务的多个线程。
- CountDownLatch对象只能被使用一次,一旦计数器为0时,如果再需要使用,则需要重新New一个CountDownLatch对象。
0 0
- java多线程 等待多个并发事件的完成
- java多线程 等待多个并发事件的完成【转】
- 并发编程--等待多个并发事件的完成
- Java并发编程-12-等待多个并发事件的完成-CountDownLatch
- 等待多个并发事件完成的模型
- [笔记][Java7并发编程实战手册]3.4 等待多个并发事件的完成CountDownLatch倒计数闭锁
- Java7并发编程--3.2、CountDownLatch等待多个并发事件完成
- 2.8.等待多个并发完成
- [Java并发]使用CountDownLatch和CyclicBarrier等待多线程完成
- 并发工具类(一)等待多线程完成的CountDownLatch
- 并发工具类(一)等待多线程完成的CountDownLatch
- 等待多线程完成的CountDownLatch
- 多线程并发访问,等待同一事件退出。
- JAVA多线程—CountDownLatch-一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
- 并发工具类:等待多线程完成的CountDownLatch,和join的区别
- java多线程的等待
- 等待多线程全部完成的方法
- (三)线程同步工具集_3---等待多个并发事件
- Meegopad、计算棒、光棍一号等,连接大容量移动硬盘的专用7*24小时资源共享经验
- 杂
- BZOJ 2038 小Z的袜子(莫队算法)
- spring前端显示
- 无限分类
- java多线程 等待多个并发事件的完成
- VS2013配置openNI1.5
- The Java™ Tutorials — Concurrency :Thread Interference 线程冲突
- C++11 转移语义 (Move Sementics) 和精确传递 (Perfect Forwarding)
- eclipse自定义设置tab页切换快捷键
- CodeForces 219A k-String
- Queen -- Android端用户数据采集新方式
- 数据结构:二叉树
- 【Android开发小记--20】读取与写入XML格式数据