等待多个并发事件完成的模型
2016-05-16 23:57
543 查看
简单的一个常见问题:如下 一个人刷牙3分钟,洗脸1分钟,梳头1分钟,煮鸡蛋5分钟。完成这些事情最少多少时间? 这其实对应编程来说就对应了题目的问题了,如何让主线程计算出多个并发事件完成的时间问题了。 我们下面会接触一个java类,那就是CountDownLatch 类,详细内容后面有时间详细添加,先下面给出一个案例代码。 下面代码只创建2个任务线程,计算完成任务最少的时间。
package test; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.CountDownLatch; public class Test { public static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static void main(String[] args) { long start =new Date().getTime(); CountDownLatch latch=new CountDownLatch(2);//两个任务 DoSomething DoSomething1=new DoSomething("刷牙", 3000, latch);//模拟3秒代表3分钟 DoSomething DoSomething2=new DoSomething("煮鸡蛋", 5000, latch);//模拟5秒代表5分钟 DoSomething1.start(); DoSomething2.start(); try { latch.await(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }//等待所有任务完成 System.out.println("总用时: "+(new Date().getTime()-start)/1000 +"秒"); } public static class DoSomething extends Thread{ String jobName; int needTime; CountDownLatch latch; public DoSomething(String jobName ,int needTime ,CountDownLatch latch){ this.jobName=jobName; this.needTime=needTime; this.latch=latch; } public void run(){ System.out.println(sdf.format(new Date())+": "+jobName+"开始"); try { Thread.sleep(needTime); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ System.out.println(sdf.format(new Date())+": "+jobName+"结束"); latch.countDown();//一个任务完成 } } } }
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树