![]() |
VOOZH | about |
Phaser's primary purpose is to enable synchronization of threads that represent one or more phases of activity. It lets us define a synchronization object that waits until a specific phase has been completed. It then advances to the next phase until that phase concludes. It can also be used to synchronize a single phase, and in that regard, it acts much like a CyclicBarrier.
Class Hierarchy
java.lang.Object ? java.util.concurrent ? Class Phaser
Syntax
public class Phaser extends Object
Constructors:
public Phaser()
public Phaser(int parties) throws IllegalArgumentException
public Phaser(Phaser parent)
public Phaser(Phaser parent, int parties) throws IllegalArgumentException
Example1:
Note: Output may vary with each run.
Starting Thread: B Phase Zero Started Thread: A Phase Zero Started Thread: C Phase Zero Started Thread: A Phase One Started Thread: B Phase One Started Thread: C Phase One Started Phase 0 Complete Phase Zero Ended Phase 1 Complete Phase One Ended Thread: C Phase Two Started Thread: A Phase Two Started Thread: B Phase Two Started Phase 2 Complete Phase Two Ended Phaser is terminated
Example2:
Starting Thread: C Phase Zero Started Thread: A Phase Zero Started Thread: B Phase Zero Started Thread: B Phase One Started Thread: C Phase One Started Thread: A Phase One Started Phase 0 Complete Phase Zero Ended Phase 1 Complete Phase One Ended Thread: A Phase Two Started Thread: C Phase Two Started Thread: B Phase Two Started Phase 2 Complete Phase Two Ended Phaser is terminated
Methods:
public int register() throws IllegalArgumentException
public int arrive() throws IllegalStateException
public int arriveAndDeregister() throws IllegalStateException
public int arriveAndAwaitAdvance() throws IllegalStateException
public final int getPhase()
protected boolean onAdvance(int phase, int parties)
Example to demonstrate the methods of Phaser class - where the method is overridden so that the phaser executes only a specified number of phases.
Starting Thread B Beginning Phase 0 Thread C Beginning Phase 0 Thread A Beginning Phase 0 Phase 0 completed. Thread A Beginning Phase 1 Thread B Beginning Phase 1 Thread C Beginning Phase 1 Phase 1 completed. Thread C Beginning Phase 2 Thread A Beginning Phase 2 Thread B Beginning Phase 2 Phase 2 completed. Thread A Beginning Phase 3 Thread B Beginning Phase 3 Thread C Beginning Phase 3 Phase 3 completed. The phaser is terminated
Reference: https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/Phaser.html