forked from akash-coded/C133-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReentrantMonitors.java
63 lines (51 loc) · 1.31 KB
/
ReentrantMonitors.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
class Warehouse {
int items = 4;
synchronized int increment(int x) {
System.out.println("Incremented to=>" + (items + x));
items += x;
return decrement(1);
}
synchronized int decrement(int x) {
if (items >= x) {
System.out.println("Decremented to=>" + (items - x));
items -= x;
return items;
}
return 0;
}
void display() {
System.out.println("Total items in warehouse =>" + items);
}
}
class Thread5 extends Thread {
Warehouse warehouse;
public Thread5(Warehouse warehouse) {
this.warehouse = warehouse;
}
@Override
public void run() {
warehouse.increment(3);
}
}
class Thread6 extends Thread {
Warehouse warehouse;
public Thread6(Warehouse warehouse) {
this.warehouse = warehouse;
}
@Override
public void run() {
warehouse.decrement(2);
}
}
public class ReentrantMonitors {
public static void main(String[] args) throws InterruptedException {
Warehouse warehouse = new Warehouse();
Thread5 thread5 = new Thread5(warehouse);
Thread6 thread6 = new Thread6(warehouse);
thread5.start();
thread6.start();
thread5.join();
thread6.join();
warehouse.display();
}
}