码迷,mamicode.com
首页 > 其他好文 > 详细

同步工具类

时间:2014-07-27 22:51:09      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   io   for   art   工作   

1.CountDownLatch

作用:使一个或多个线程等待一组事件发生。

包括一个计数器,初始化为一个正数,表示需要等待的事件数量。

countDown方法递减计数器,表示有一个事件已经发生了。

await方法等待计数器为零,这表示所有需要等待的事件都已经发生。

public class TestHarness {
    public long timeTasks(int nThreads, final Runnable task)
            throws InterruptedException {
        final CountDownLatch startGate = new CountDownLatch(1);
        final CountDownLatch endGate = new CountDownLatch(nThreads);

        for (int i = 0; i < nThreads; i++) {
            Thread t = new Thread() {
                public void run() {
                    try {
                        startGate.await();
                        try {
                            task.run();
                        } finally {
                            endGate.countDown();
                        }
                    } catch (InterruptedException ignored) {
                    }
                }
            };
            t.start();
        }

        long start = System.nanoTime();
        startGate.countDown();
        endGate.await();
        long end = System.nanoTime();
        return end - start;
    }
}

使用了两个闭锁:起始门 结束门

在起始门上等待,确保所有线程都就绪后才开始执行。结束门确保使主线程高效地等待直到所有工作线程都执行完成。

2.CyclicBarrier

 

同步工具类,布布扣,bubuko.com

同步工具类

标签:style   blog   color   使用   io   for   art   工作   

原文地址:http://www.cnblogs.com/scofield0li/p/3871682.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!