0

假设所有线程都在 java Phaser 的第 0 阶段工作,那么一个线程arrive(); arrive(); arriveAndAwaitAdvance();会不会等待 Phaser 结束第 2 阶段或第 0 阶段?

4

1 回答 1

0

这取决于 Phaser 上的线程(参与方)的数量。简单的移相器将在推进阶段之前等待一些到达()。

如果您将移相器设置为 2 方,将会发生以下情况:

  1. 首先,到达()不会改变阶段,因为我们需要 2。
  2. 第二次到达()会将相位从 0 更改为 1。
  3. 到达AndAwaitAdvance() 操作不会将阶段从 1 更改为 2,因为我们需要 2 到达才能前进。

new Phaser(2);因此,如果您的 Phaser 中的参与方数量为 2 ( ) ,您的线程将等待阶段 1 结束。

这是一个示例代码,可以帮助您了解移相器的工作原理:

ExecutorService executorService = Executors.newFixedThreadPool(2);
Phaser phaser = new Phaser(2);

executorService.execute(() -> {
    System.out.println("First thread phase = " + phaser.getPhase());
    phaser.arrive();
    System.out.println("First thread After arrive1 = " + phaser.getPhase());
    phaser.arrive();
    System.out.println("First thread After arrive2 = " + phaser.getPhase());
    phaser.arrive();
    System.out.println("First thread After arrive3 = " + phaser.getPhase());
    phaser.arrive();
    System.out.println("First thread After arrive4 = " + phaser.getPhase());
    phaser.arriveAndAwaitAdvance();
    System.out.println("First thread After arriveAndAwaitAdvance  = " + phaser.getPhase());
});

executorService.execute(() -> {
    try {
        Thread.sleep(2000);
        System.out.println("Second thread current phase = " + phaser.getPhase());
        phaser.arriveAndAwaitAdvance();
        System.out.println("Second thread After arriveAndAwaitAdvance = " + phaser.getPhase());
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
});
executorService.shutdown();

这段代码的输出是:

First thread phase = 0
First thread After arrive1 = 0
First thread After arrive2 = 1
First thread After arrive3 = 1
First thread After arrive4 = 2
Second thread current phase = 2
Second thread After arriveAndAwaitAdvance = 3
First thread After arriveAndAwaitAdvance  = 3

我希望这能回答你的问题。

于 2021-01-04T03:56:53.793 回答