首页 > 代码库 > 同步工具类

同步工具类

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