论坛首页 Java企业应用论坛

CountDownLatch 简单学习

浏览 2763 次
精华帖 (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 {

        }

    }
}

   发表时间:2011-07-10  
实现什么功能呢?
0 请登录后投票
   发表时间:2011-07-10  
287854442 写道
实现什么功能呢?

计算它们总共跑了多长时间啊
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics