Home > Java, Multithreading > CyclicBarrier

CyclicBarrier


CyclicBarrier = Cycle + Barrier

CyclicBarrier just force threads to wait until their count reached to N. Then release them to run on a wide road. And force next N threads to wait. and so on.

 

public class CycleBarrierDemo implements Runnable {
    CyclicBarrier controller;

    CycleBarrierDemo() {
        controller = new CyclicBarrier(1);
    }
    @Override
    public void run() {
        try {
            Thread.sleep(100);
            System.out.println(controller.getNumberWaiting());
            System.out.println(Thread.currentThread().getName() + " has been arrived");
            controller.await();
            System.out.println(Thread.currentThread().getName() + " has been Passed");
        } catch (Exception bbx) {
            System.out.println(bbx.getMessage());
        }
    }
    public static void main(String[] argc) {
        CycleBarrierDemo cd = new CycleBarrierDemo();
        Thread A = new Thread(cd, "A");
        Thread B = new Thread(cd, "B");
        Thread C = new Thread(cd, "C");
        Thread D = new Thread(cd, "D");

        A.start();
        B.start();
        C.start();
        D.start();
    }
}

Output: [When barrier size was 1]

0
A has been arrived
A has been Passed
0
B has been arrived
B has been Passed
0
C has been arrived
C has been Passed
0
D has been arrived
D has been Passed

Output:[When barrier size was 2]

A has been arrived
1
B has been arrived
A has been Passed
B has been Passed
0
C has been arrived
1
D has been arrived
C has been Passed
D has been Passed

Advertisements
Categories: Java, Multithreading
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: