Skip to content

Commit 9a82c3f

Browse files
committed
Use CyclicBarrier to make it happen
1 parent f9372d7 commit 9a82c3f

2 files changed

Lines changed: 27 additions & 7 deletions

File tree

BarrierExample.java

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,14 @@
1+
import java.util.concurrent.CyclicBarrier;
2+
13
public 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

Worker.java

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,29 @@
1+
import java.util.concurrent.CyclicBarrier;
2+
import java.util.concurrent.BrokenBarrierException;
3+
14
public 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
}

0 commit comments

Comments
 (0)