-
Notifications
You must be signed in to change notification settings - Fork 0
/
bakery.java
60 lines (50 loc) · 1.56 KB
/
bakery.java
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
public class Bakery {
public static boolean[] flag;
public static int [] label;
public static int sharecounter=0;
public static int thread_num=8;
public static void main(String[] args) {
int repeat = 0;
flag = new boolean[thread_num];
label = new int[thread_num];
for (int i = 0; i < thread_num; i++) { flag[i] = false; label[i] = 0; }
for(int i=0;i<thread_num;i++){
repeat=100; // the number of repeat time can be set here
BakeryThread bt = new BakeryThread(i,repeat,sharecounter);
Thread t = new Thread(bt);
t.start();
}
}
public static class BakeryThread implements Runnable {
private int id;
private int repeat;
private int count;
public BakeryThread(int id, int repeat, int count) {
this.id = id;
this.repeat=repeat;
this.count = count;
}
public void lock(int pid) {
flag[pid] = true;
int max=0;
for (int n : label) { if (n > max) { max = n; } }
label[pid] = max + 1;
for (int k=0; k<label.length;k++){
while ((k != pid) && (flag[k] && ((label[k] < label[pid]) || ((label[pid] == label[k]) && k < pid) ))){
Thread.yield();
}
}
}
public void unlock(int pid) {
flag[pid] = false;
}
public void run() {
for (int i = 0; i < repeat; i++) {
lock(id);
sharecounter+=1;
System.out.println("previous counter: "+count+" shared counter: "+sharecounter);
unlock(id);
}
}
}
}