Skip to content

Latest commit

 

History

History
83 lines (63 loc) · 2.28 KB

File metadata and controls

83 lines (63 loc) · 2.28 KB

Phaser

  • Synchronizes threads that represent one or more phases of activity.
  • it can also be used to synchronize a single phase, in which case it acts like a cyclicbarrier.
import java.util.concurrent.Phaser;


class Task implements Runnable {
    Phaser phaser;

    Task(Phaser phaser){
        this.phaser = phaser;
        this.phaser.register();
    }

    /**
     * Runs this operation.
     */
    @Override
    public void run() {
        String name = Thread.currentThread().getName();

        System.out.println("Thread " + name + ">> Beginning Phase one");
        this.phaser.arriveAndAwaitAdvance(); // signal arrival

        try{
            Thread.sleep(100);
        }catch (InterruptedException ex){
            System.out.println(ex.getCause());
        }

        System.out.println("Thread " + name + ">> Beginning Phase two");
        this.phaser.arriveAndAwaitAdvance(); // signal arrival
        try{
            Thread.sleep(100);
        }catch (InterruptedException ex){
            System.out.println(ex.getCause());
        }

        System.out.println("Thread " + name + ">> Beginning Phase three");
        this.phaser.arriveAndDeregister(); // signal arrival and deregister
    }
}

public class Main {

    public static void main(String[] args) {
        Phaser phaser = new Phaser(1);
        int currentPhase;
        System.out.println("starting");

        new Thread(new Task(phaser),"A").start();
        new Thread(new Task(phaser),"B").start();
        new Thread(new Task(phaser),"C").start();

        // wait for phase one to complete
        currentPhase = phaser.getPhase();
        phaser.arriveAndAwaitAdvance();
        System.out.println("Phase >> " + currentPhase + " Complete");

        // wait for phase two to complete
        currentPhase = phaser.getPhase();
        phaser.arriveAndAwaitAdvance();
        System.out.println("Phase >> " + currentPhase + " Complete");

        // wait for phase three to complete
        currentPhase = phaser.getPhase();
        phaser.arriveAndAwaitAdvance();
        System.out.println("Phase >> " + currentPhase + " Complete");

        // deregister the main thread
        phaser.arriveAndDeregister();

        if(phaser.isTerminated()){
            System.out.println("The phaser is terminated");
        }
    }
}