Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package javacore.threading;
- import java.util.concurrent.BrokenBarrierException;
- import java.util.concurrent.CyclicBarrier;
- public class CyclicBarrierExample {
- private static class Task implements Runnable{
- private CyclicBarrier barrier;
- public Task(CyclicBarrier barrier){
- this.barrier = barrier;
- }
- @Override
- public void run() {
- try{
- System.out.println(Thread.currentThread().getName() + " is waiting on barrier");
- barrier.await();
- System.out.println(Thread.currentThread().getName() + " has crossed the barrier");
- }catch(InterruptedException ex){
- ex.printStackTrace();
- }catch(BrokenBarrierException ex){
- ex.printStackTrace();
- }
- }
- }
- public static void main(String args[]) {
- //creating CyclicBarrier with 4 parties i.e. 4 Threads needs to call await()
- final CyclicBarrier cb = new CyclicBarrier(4, new Runnable(){
- @Override
- public void run(){
- //This task will be executed once all thread reaches barrier
- System.out.println("All parties are arrived at barrier, lets play");
- }
- });
- //starting each of thread
- Thread t1 = new Thread(new Task(cb), "Thread 1");
- Thread t2 = new Thread(new Task(cb), "Thread 2");
- Thread t3 = new Thread(new Task(cb), "Thread 3");
- Thread t4 = new Thread(new Task(cb), "Thread 4");
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
Add Comment
Please, Sign In to add comment