forked from Java2ArkTS/Java2ArkTS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBus.java
More file actions
87 lines (75 loc) · 2.16 KB
/
Copy pathBus.java
File metadata and controls
87 lines (75 loc) · 2.16 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
/*
* The activities of bus drivers and conductors are as follows:
* Driver's activities: start the vehicle, run normally, stop at the station.
* Conductor's activities: Close doors, sell tickets, open doors.
* The car constantly arrives at the station, stops, and drives,
* realizing the synchronization of the driver and the conductor.
*/
public class Bus {
public static void main(String[] args) {
Semaphores semaphores = new Semaphores();
Thread driver = new Thread(new Driver(semaphores));
Thread conductor = new Thread(new Conductor(semaphores));
driver.start();
conductor.start();
}
}
class Semaphores {
public boolean s1 = false;
public boolean s2 = false;
public synchronized boolean ps1() {
if (s1) {
s1 = false;
return true;
} else {
return false;
}
}
public synchronized boolean ps2() {
if (s2) {
s2 = false;
return true;
} else {
return false;
}
}
public synchronized void vs1() {
s1 = true;
}
public synchronized void vs2() {
s2 = true;
}
}
class Driver implements Runnable {
public Semaphores semaphores;
public Driver(Semaphores semaphores) {
this.semaphores = semaphores;
}
public void run() {
while (true) {
while (!semaphores.ps1()) {
}
System.out.println("Bus starts.");
System.out.println("Driver is driving.");
System.out.println("Bus stops.");
semaphores.vs2();
}
}
}
class Conductor implements Runnable {
public Semaphores semaphores;
public Conductor(Semaphores semaphores) {
this.semaphores = semaphores;
}
public void run() {
while (true) {
System.out.println("Conductor closes the door.");
semaphores.vs1();
System.out.println("Conductor sells tickets.");
while (!semaphores.ps2()) {
}
System.out.println("Conductor opens the door.");
System.out.println("Customers get on/off the bus.");
}
}
}