-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCyclicBarrierDemo.java
More file actions
111 lines (94 loc) · 2.23 KB
/
Copy pathCyclicBarrierDemo.java
File metadata and controls
111 lines (94 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierDemo{
public static void main(String[] args){
float[][] matrix = new float[3][3];
int counter = 0;
for(int row=0;row<matrix.length;row++){
for(int col =0 ; col<matrix[0].length; col++){
matrix[row][col] = counter++;
}
}
dump(matrix);
System.out.println();
Solver solver = new Solver(matrix);
System.out.println();
dump(matrix);
}
static void dump(float[][] matrix){
for(int row =0;row<matrix.length;row++){
for(int col=0;col<matrix[0].length;col++){
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
}
}
class Solver{
final int N;
final float[][] data;
final CyclicBarrier barrier;
class WorkerTask implements Runnable{
int myRow;
boolean done = false;
WorkerTask(int row){
myRow = row;
}
boolean done(){
return done;
}
void processRow(int myRow){
System.out.println(Thread.currentThread() + " processing row: " + myRow);
for(int i=0;i<data[myRow].length;i++){
data[myRow][i]*=10;
}
done = true;
}
@Override
public void run(){
while(!done()){
processRow(myRow);
try{
barrier.await(); // Not tripped till all parties wait at the barrier :)
}catch(InterruptedException ie){
ie.printStackTrace();
return;
}catch(BrokenBarrierException bbe){
bbe.printStackTrace();
return;
}
}
}
}
public Solver(float[][] matrix){
data = matrix;
N = matrix.length;
barrier = new CyclicBarrier(N, new Runnable(){
@Override
public void run(){
mergeRows(); // execute when the barrier tripped.
}
});
for(int i=0;i<N;i++){
new Thread(new WorkerTask(i)).start();
}
waitUntilDone();
}
void mergeRows(){
System.out.println(Thread.currentThread() + "merging simulating.");
synchronized("abc"){
"abc".notify();
}
}
void waitUntilDone(){
synchronized("abc"){
try{
System.out.println(Thread.currentThread() + " is waiting.");
"abc".wait();
System.out.println(Thread.currentThread() + " is notified.");
}catch(InterruptedException ie){
System.out.println(Thread.currentThread() + " is interrupted.");
}
}
}
}