java - java中哪里使用屏障模式?

标签 java phaser

我刚刚阅读了有关 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/

相关文章:

java - Hibernate用户更新删除用户角色

java - Phaser - 如何将其用作 CountDownLatch(1)?

java - 如何正确使用Phaser?

java - 使用 FTP 进行文件传输的代码可以打开或关闭多个连接吗?

java - 当同一类的不同实例在总线上注册时,Guava EventBus 抛出 handlerExcetion

Java LWJGL OGG 背景音乐

java - ForkJoinPool、Phaser 和托管阻塞 : to what extent do they works against deadlocks?

java - RESTful Web 应用程序是什么意思?

java - 使用和重用 Phaser 而不是 join()

java - 我如何知道最后一方何时触发 Phaser.arrive()?