Guest User

Untitled

a guest
Dec 15th, 2017
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. package javacore.threading;
  2.  
  3. import java.util.concurrent.BrokenBarrierException;
  4. import java.util.concurrent.CyclicBarrier;
  5.  
  6. public class CyclicBarrierExample {
  7.  
  8. private static class Task implements Runnable{
  9.  
  10. private CyclicBarrier barrier;
  11.  
  12. public Task(CyclicBarrier barrier){
  13. this.barrier = barrier;
  14. }
  15.  
  16. @Override
  17. public void run() {
  18.  
  19. try{
  20. System.out.println(Thread.currentThread().getName() + " is waiting on barrier");
  21. barrier.await();
  22. System.out.println(Thread.currentThread().getName() + " has crossed the barrier");
  23.  
  24. }catch(InterruptedException ex){
  25. ex.printStackTrace();
  26. }catch(BrokenBarrierException ex){
  27. ex.printStackTrace();
  28. }
  29. }
  30. }
  31.  
  32. public static void main(String args[]) {
  33.  
  34. //creating CyclicBarrier with 4 parties i.e. 4 Threads needs to call await()
  35. final CyclicBarrier cb = new CyclicBarrier(4, new Runnable(){
  36. @Override
  37. public void run(){
  38. //This task will be executed once all thread reaches barrier
  39. System.out.println("All parties are arrived at barrier, lets play");
  40. }
  41. });
  42.  
  43. //starting each of thread
  44. Thread t1 = new Thread(new Task(cb), "Thread 1");
  45. Thread t2 = new Thread(new Task(cb), "Thread 2");
  46. Thread t3 = new Thread(new Task(cb), "Thread 3");
  47. Thread t4 = new Thread(new Task(cb), "Thread 4");
  48.  
  49. t1.start();
  50. t2.start();
  51. t3.start();
  52. t4.start();
  53.  
  54. }
  55. }
Add Comment
Please, Sign In to add comment