File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import java .util .concurrent .CyclicBarrier ;
2+
13public class BarrierExample {
24
35 public static void main (String args []){
4- for (int i =0 ; i <50 ; i ++) {
5- new Thread (new Worker ()).start ();
6+ int numThreads = 10 ;
7+
8+ final CyclicBarrier b = new CyclicBarrier (numThreads );
9+
10+ for (int i =0 ; i <numThreads ; i ++) {
11+ new Thread (new Worker (b )).start ();
612 }
713 }
814
Original file line number Diff line number Diff line change 1+ import java .util .concurrent .CyclicBarrier ;
2+ import java .util .concurrent .BrokenBarrierException ;
3+
14public class Worker implements Runnable {
25
6+ private CyclicBarrier barrier ;
7+ public Worker (CyclicBarrier barrier ) {
8+ this .barrier = barrier ;
9+ }
10+
311 public void log (String message ) {
412 System .out .println (Thread .currentThread ().getName () + ": " + message );
513 }
614
7- public void run (){
8- log ("running" );
9- log ("this should happen before reaching the barrier" );
15+ public void run () {
16+ try {
17+ log ("running" );
18+ log ("this should happen before reaching the barrier" );
1019
11- // TODO: insert barrier here
12- log ("this should happen after the barrier" );
20+ barrier .await ();
21+ log ("this should happen after the barrier" );
22+ } catch (InterruptedException ex ) {
23+ log ("damn I hate interrupts! Committing suicide: " + ex );
24+ } catch (BrokenBarrierException ex ) {
25+ log ("damn, the dam burst: " + ex );
26+ }
1327 }
1428
1529}
You can’t perform that action at this time.
0 commit comments