-
Notifications
You must be signed in to change notification settings - Fork 0
/
SafeRace.java
44 lines (37 loc) · 882 Bytes
/
SafeRace.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
import util.Lock;
public class SafeRace {
private final Lock lock = new Lock();
private int counter = 0;
public static void main(String[] args) {
SafeRace race = new SafeRace();
int result = race.run();
System.out.println("Result: " + result);
}
public int run() {
Thread inc = new ThreadImpl(1);
Thread dec = new ThreadImpl(-1);
inc.start();
dec.start();
try {
inc.join();
dec.join();
return counter;
} catch (InterruptedException unused) {
return 0;
}
}
private class ThreadImpl extends Thread {
private static final int OPS = 1000000;
private final int delta;
ThreadImpl(int delta) {
this.delta = delta;
}
@Override public void run() {
for (int i = 0; i < OPS; i++) {
lock.acquire();
counter += delta;
lock.release();
}
}
}
}