我刚刚阅读了有关 Phaser
的 javadoc there并对该类的使用有疑问。 javadoc 提供了一个示例,但是现实生活中的示例呢?这样的屏障实现在实践中可能有用吗?
最佳答案
我没有使用过Phaser
,但我使用过CountDownLatch
。引用的文档说:
[
Phaser
is] similar in functionality to ...CountDownLatch
but supporting more flexible usage.
CountDownLatch
在您触发多个线程来执行某些任务的任何地方都很有用,在老式学校中,您会使用 Thread.join()
来等待它们完成。
例如:
老派:
Thread t1 = new Thread("one");
Thread t2 = new Thread("two");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Both threads have finished");
使用CountDownLatch
public class MyRunnable implement Runnable {
private final CountDownLatch c; // Set this in constructor
public void run() {
try {
// Do Stuff ....
} finally {
c.countDown();
}
}
}
<小时/>
CountDownLatch c = new CountDownLatch(2);
executorService.submit(new MyRunnable("one", c));
executorService.submit(new MyRunnable("two", c));
c.await();
System.out.println("Both threads have finished");
关于java - java中哪里使用屏障模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28659314/