1

我刚刚阅读了关于Phaser 那里的javadoc,并且对该类的用法有疑问。javadoc 提供了一个示例,但现实生活中的示例呢?这样的屏障实现在实践中在哪里有用?

4

1 回答 1

1

我没用过Phaser,但我用过CountDownLatch。引用的文档说:

[ Phaseris] 功能类似于 ...CountDownLatch但支持更灵活的使用。

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");
于 2016-08-18T23:18:19.523 回答