-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNoRace.java
More file actions
37 lines (30 loc) · 777 Bytes
/
NoRace.java
File metadata and controls
37 lines (30 loc) · 777 Bytes
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
class Counter {
int count = 0;
synchronized void increment() {
count++; // now thread-safe
}
}
public class NoRace {
public static void main(String[] args) {
Counter c = new Counter();
Thread t1 = new Thread(() -> {
for(int i = 0; i < 1000; i++) {
c.increment();
}
});
Thread t2 = new Thread(() -> {
for(int i = 0; i < 1000; i++) {
c.increment();
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (Exception e) {
System.out.println("Thread interrupted: " + e.getMessage());
}
System.out.println("Count: " + c.count);
}
}