1

Phaser そこについてのjavadocを読んだところですが、そのクラスの使用法について質問があります。javadoc はサンプルを提供しますが、実際の例はどうでしょうか? そのようなバリアの実装が実際に役立つのはどこですか?

4

1 に答える 1

1

は使っていませんがPhaser、使っていCountDownLatchます。参照されたドキュメントには次のように書かれています:

[Phaserは] ... と機能的に似ています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 に答える