-
Notifications
You must be signed in to change notification settings - Fork 1
/
RaceCondition2.java
69 lines (55 loc) · 1.88 KB
/
RaceCondition2.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
60
61
62
63
64
65
66
67
68
69
package com.jyotindersingh;
public class RaceCondition2 {
@SuppressWarnings("DuplicatedCode")
public static void main(String[] args) throws InterruptedException {
InventoryCounter inventoryCounter = new InventoryCounter();
IncrementingThread incrementingThread = new IncrementingThread(inventoryCounter);
DecrementingThread decrementingThread = new DecrementingThread(inventoryCounter);
incrementingThread.start();
decrementingThread.start();
incrementingThread.join();
decrementingThread.join();
System.out.println("We currently have " + inventoryCounter.getItems() + " items.");
}
private static class DecrementingThread extends Thread {
private InventoryCounter inventoryCounter;
public DecrementingThread(InventoryCounter inventoryCounter) {
this.inventoryCounter = inventoryCounter;
}
@Override
public void run() {
for (int i = 0; i < 10000; ++i) {
inventoryCounter.decrement();
}
}
}
private static class IncrementingThread extends Thread {
private InventoryCounter inventoryCounter;
public IncrementingThread(InventoryCounter inventoryCounter) {
this.inventoryCounter = inventoryCounter;
}
@Override
public void run() {
for (int i = 0; i < 10000; ++i) {
inventoryCounter.increment();
}
}
}
private static class InventoryCounter {
private int items = 0;
Object lock = new Object();
public void increment() {
synchronized (lock) {
items++;
}
}
public void decrement() {
synchronized (lock) {
items--;
}
}
public int getItems() {
return items;
}
}
}