facebook twitter youtube
by Amit Gupta - no comments

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.

Example Program:

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

Amit Gupta

Hey! this is Amit Gupta (amty). By profession, I am a Software Eng. And teaching is my passion. Sometimes I am a teacher, as you can see many technical tutorials on my site, sometimes I am a poet, And sometime just a friend of friends...

Leave a Reply

captcha