forked from Java2ArkTS/Java2ArkTS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueuingMachine.java
More file actions
115 lines (100 loc) · 2.64 KB
/
Copy pathQueuingMachine.java
File metadata and controls
115 lines (100 loc) · 2.64 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
public class QueuingMachine {
public static void main(String[] args) {
Semaphores semaphores = new Semaphores();
Thread server = new Thread(new Server(semaphores));
Thread customer1 = new Thread(new Customer(semaphores, 1));
Thread customer2 = new Thread(new Customer(semaphores, 2));
Thread customer3 = new Thread(new Customer(semaphores, 3));
Thread customer4 = new Thread(new Customer(semaphores, 4));
server.start();
customer1.start();
customer2.start();
customer3.start();
customer4.start();
}
}
class Semaphores {
public int empty = 10;
public boolean mutex = true;
public int full = 0;
public boolean service = false;
public synchronized boolean pEmpty() {
if (empty > 0) {
empty--;
return true;
} else {
return false;
}
}
public synchronized boolean pFull() {
if (full > 0) {
full--;
return true;
} else {
return false;
}
}
public synchronized boolean pMutex() {
if (mutex) {
mutex = false;
return true;
} else {
return false;
}
}
public synchronized boolean pService() {
if (service) {
service = false;
return true;
} else {
return false;
}
}
public synchronized void vEmpty() {
empty++;
}
public synchronized void vFull() {
full++;
}
public synchronized void vMutex() {
mutex = true;
}
public synchronized void vService() {
service = true;
}
}
class Customer implements Runnable {
public Semaphores semaphores;
public int rank;
public Customer(Semaphores semaphores, int rank) {
this.semaphores = semaphores;
this.rank = rank;
}
public void run() {
while (!semaphores.pEmpty()) {
}
while (!semaphores.pMutex()) {
}
System.out.println("Customer " + rank + " takes a number.");
semaphores.vMutex();
semaphores.vFull();
while (!semaphores.pService()) {
}
System.out.println("Customer " + rank + " gets service.");
}
}
class Server implements Runnable {
public Semaphores semaphores;
public Server(Semaphores semaphores) {
this.semaphores = semaphores;
}
public void run() {
while (true) {
while (!semaphores.pFull()) {
}
semaphores.vEmpty();
semaphores.vService();
System.out.println("Server serves.");
}
}
}