Phaser Dynamic Party Registration
Coordinate multi-phase group progression with Phaser: register workers on the fly, wait for every party each round, and deregister finishers.
Code
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
public class ReleaseTrain {
public static void main(String[] args) throws InterruptedException {
// 主线程自己也占一个名额:1 + 动态注册的 worker
Phaser phaser = new Phaser(1);
ExecutorService pool = Executors.newFixedThreadPool(3);
for (int i = 1; i <= 3; i++) {
phaser.register(); // worker 动态加入
int worker = i;
pool.submit(() -> {
for (int phase = 0; phase < 2; phase++) {
phaser.arriveAndAwaitAdvance(); // 等齐所有参与方再进入下一阶段
System.out.println("worker " + worker + " done with phase " + phase);
}
phaser.arriveAndDeregister(); // 干完自己的阶段就退出
});
}
phaser.arriveAndAwaitAdvance(); // 第 0 阶段放行
phaser.arriveAndAwaitAdvance(); // 第 1 阶段放行
System.out.println("phase advanced to " + phaser.getPhase());
phaser.arriveAndDeregister(); // 主线程退出,注册数归零后 Phaser 终止
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
}
}How it works
Count the class ReleaseTrain as the entire surface area of Phaser Dynamic Party Registration.
Iteration happens inside for (int i = 1; i <= 3; i++) — everything outside it runs once.
Putting it to use
Running the file prints labeled results such as worker, phase advanced to — each operation’s effect is visible in the output.
Core lines
ExecutorService pool = Executors.newFixedThreadPool(3);
Interactive Tools for This Topic
FAQ
- What does Phaser Dynamic Party Registration print when run?
- Execute the whole file; each printed line is prefixed with a label like `worker`, `phase advanced to`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.