首页 > 代码库 > 同步工具类
同步工具类
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。