-
Notifications
You must be signed in to change notification settings - Fork 2
/
RaceCondition.java
63 lines (49 loc) · 1.73 KB
/
RaceCondition.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
package com.jyotindersingh;
public class RaceCondition {
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;
public synchronized void increment() {
items++;
}
public synchronized void decrement() {
items--;
}
public int getItems() {
return items;
}
}
}