forked from Java2ArkTS/Java2ArkTS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInventoryManagementTest.java
More file actions
71 lines (58 loc) · 1.84 KB
/
Copy pathInventoryManagementTest.java
File metadata and controls
71 lines (58 loc) · 1.84 KB
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
70
71
class Inventory {
private int stock;
public Inventory(int initialStock) {
this.stock = initialStock;
}
public synchronized void addStock(int amount) {
stock += amount;
System.out.println(" added " + amount + " units. Current stock: " + stock);
}
public synchronized void removeStock(int amount) {
if (amount <= stock) {
stock -= amount;
System.out.println(" removed " + amount + " units. Current stock: " + stock);
} else {
System.out.println(" tried to remove " + amount + " units, but only " + stock + " units available.");
}
}
public synchronized int getStock() {
return stock;
}
}
class AddStockTask implements Runnable {
private Inventory inventory;
private int amount;
public AddStockTask(Inventory inventory, int amount) {
this.inventory = inventory;
this.amount = amount;
}
@Override
public void run() {
inventory.addStock(amount);
}
}
class RemoveStockTask implements Runnable {
private Inventory inventory;
private int amount;
public RemoveStockTask(Inventory inventory, int amount) {
this.inventory = inventory;
this.amount = amount;
}
@Override
public void run() {
inventory.removeStock(amount);
}
}
public class InventoryManagementTest {
public static void main(String[] args) {
Inventory inventory = new Inventory(100);
Thread thread1 = new Thread(new AddStockTask(inventory, 30));
Thread thread2 = new Thread(new RemoveStockTask(inventory, 50));
Thread thread3 = new Thread(new AddStockTask(inventory, 20));
Thread thread4 = new Thread(new RemoveStockTask(inventory, 70));
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}