簡單的一個常見問題:以下 一我的刷牙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();//一個任務完成 } } } }
http://bbs.bxzc123.com/forum.php?mod=viewthread&tid=244545
http://bbs.bxzc123.com/forum.php?mod=viewthread&tid=244541
http://bbs.bxzc123.com/forum.php?mod=viewthread&tid=244538
http://bbs.bxzc123.com/forum.php?mod=viewthread&tid=244527
http://bbs.bxzc123.com/forum.php?mod=viewthread&tid=244528
http://bbs.bxzc123.com/forum.php?mod=viewthread&tid=244529
http://bbs.bxzc123.com/forum.php?mod=viewthread&tid=244530php