浏览 2763 次
锁定老帖子 主题:CountDownLatch 简单学习
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (1)
|
|
---|---|
作者 | 正文 |
发表时间:2011-07-08
最后修改:2011-07-08
import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; public class TestCountDownLatch { private static List<String> mans = new ArrayList<String>(); private static CyclicBarrier barrier = null; private static AtomicInteger costTimes = new AtomicInteger(0); static { mans.add("andy"); mans.add("jack"); mans.add("lili"); mans.add("alan"); mans.add("bill"); barrier = new CyclicBarrier(mans.size() + 1); } public static class Walk implements Runnable { private AtomicInteger ct = new AtomicInteger(0); private String name; private CountDownLatch latch; public Walk(String name, AtomicInteger countTime, CountDownLatch cdl) { ct = countTime; this.name = name; latch = cdl; } @Override public void run() { int walkTime = new Random().nextInt(20); try { if ("lili".equals(name)) { Thread.sleep(10000); } else Thread.sleep(1000); } catch (InterruptedException e) { } System.out.println(name + " walk " + walkTime + "min"); ct.addAndGet(walkTime); try { // barrier.await(); latch.countDown(); } catch (Exception e) { } System.out.println(name + " walk over!"); } } public static void main(String[] args) { try { CountDownLatch latch = new CountDownLatch(mans.size()); ExecutorService es = Executors.newFixedThreadPool(mans.size()); for (String str : mans) { es.submit(new Walk(str, costTimes, latch)); } es.shutdown(); latch.await(); //barrier.await(); System.out.println("TOTAL COST:" + costTimes + "min"); } catch (Exception e) { System.out.println(e.getMessage()); } finally { } } } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2011-07-10
实现什么功能呢?
|
|
返回顶楼 | |
发表时间:2011-07-10
287854442 写道 实现什么功能呢?
计算它们总共跑了多长时间啊 |
|
返回顶楼 | |