Created
July 27, 2010 19:05
-
-
Save harikrishnan83/492686 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* An example to illustrate the CyclicBarrier in java.util.concurrent package. | |
* Here we are creating a barrier to an entry for a coding session. | |
* A minimum of three programmers are necessary to start the coding session. | |
*/ | |
import java.util.concurrent.BrokenBarrierException; | |
import java.util.concurrent.CyclicBarrier; | |
public class CodingDojo { | |
private CyclicBarrier entryBarrier; | |
private CyclicBarrier exitBarrier; | |
public CodingDojo(int count) { | |
int minimumPartyPeople = count; | |
entryBarrier = new CyclicBarrier(minimumPartyPeople); | |
} | |
public void enter() { | |
System.out.println(Thread.currentThread().getName() + " has arrived at the coding dojo "); | |
try { | |
entryBarrier.await(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} catch (BrokenBarrierException e) { | |
e.printStackTrace(); | |
} | |
System.out.println(Thread.currentThread().getName() + "Started Coding"); | |
System.out.println(Thread.currentThread().getName() + "Leaving Dojo"); | |
} | |
public static void main(String args[]) throws InterruptedException { | |
CodingDojo barrierSample = new CodingDojo(3); | |
Thread thread1 = new Thread(new Programmer(barrierSample), "Sai"); | |
Thread thread2 = new Thread(new Programmer(barrierSample), "Hari"); | |
Thread thread3 = new Thread(new Programmer(barrierSample), "Raja"); | |
thread1.start(); | |
Thread.sleep(1000); | |
thread2.start(); | |
Thread.sleep(1000); | |
thread3.start(); | |
} | |
} | |
class Programmer implements Runnable { | |
private final CodingDojo barrierSample; | |
public Programmer(CodingDojo barrierSample) { | |
this.barrierSample = barrierSample; | |
} | |
@Override | |
public void run() { | |
barrierSample.enter(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment