package synchronisers;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierExample {

    public static void main(String[] args) {
        final CyclicBarrier barrier = new CyclicBarrier(3);
        //Like Datona Racing - wait for 3 players before continuing.
        System.out.println("This game requires three players.");        
        System.out.println("Waiting for Player 1...");
        try { Thread.sleep(4000);} catch (InterruptedException ex) {}

        //First Thread calls barrier.await()
        new Thread() {
            public void run() {
                try {
                    System.out.println("Player 1 has joined");
                    barrier.await();
                    System.out.println("Player 1 is go!");
                } catch (BrokenBarrierException|InterruptedException ex) {

                }
            }
        }.start();
        try {Thread.sleep(10);} catch (InterruptedException ex) {}
        
        System.out.println("Waiting for player 2...");

        try { Thread.sleep(4000);} catch (InterruptedException ex) {}
        
        //Second Thread calls barrier.await().
        new Thread() {
            public void run() {
                try {
                    System.out.println("Player 2 has joined");
                    barrier.await();
                    System.out.println("Player 2 is go!");
                } catch (BrokenBarrierException|InterruptedException ex) {

                }
            }
        }.start();
        try {Thread.sleep(10);} catch (InterruptedException ex) {}
        
        System.out.println("Waiting for player 3...");

        try { Thread.sleep(2000);} catch (InterruptedException ex) {}
        
        //Third Thread calls barrier.await().  Should relaease other two threads.
        new Thread() {
            public void run() {
                try {
                    System.out.println("Player 3 has joined");
                    barrier.await();
                    System.out.println("Player 3 is go!");
                } catch (BrokenBarrierException|InterruptedException ex) {

                }
            }
        }.start();
    }
}