forked from Java2ArkTS/Java2ArkTS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrafficLightProblem.java
More file actions
96 lines (81 loc) · 3 KB
/
Copy pathTrafficLightProblem.java
File metadata and controls
96 lines (81 loc) · 3 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
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class TrafficLightProblem {
public static void main(String[] args) {
Intersection intersection = new Intersection();
// 创建多个车辆线程
for (int i = 1; i <= 10; i++) {
Thread vehicleThread = new Thread(new VehicleClass(intersection, i), "Vehicle " + i);
vehicleThread.start();
}
// 模拟交通灯变化
for (int i = 0; i < 5; i++) {
intersection.changeLight(); // 改变交通灯
try {
Thread.sleep(3000); // 模拟灯变化的时间间隔
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 中断所有车辆线程
for (Thread thread : Thread.getAllStackTraces().keySet()) {
if (thread.getName().startsWith("Vehicle")) {
thread.interrupt();
}
}
}
// 交通路口类
static class Intersection {
private AtomicBoolean greenLight = new AtomicBoolean(true); // 初始为绿灯
private AtomicInteger waitingCount = new AtomicInteger(0); // 等待通行的车辆数量
// 改变交通灯状态
void changeLight() {
greenLight.set(!greenLight.get());
if (greenLight.get()) {
System.out.println("Traffic light changes to green.");
} else {
System.out.println("Traffic light changes to red.");
}
synchronized (this) {
notifyAll(); // 唤醒所有等待的车辆
}
}
// 判断交通灯是否为绿灯
boolean isGreen() {
return greenLight.get();
}
// 车辆等待通行
synchronized void waitToPass() throws InterruptedException {
waitingCount.incrementAndGet();
while (!isGreen()) {
wait(); // 等待绿灯
}
waitingCount.decrementAndGet();
}
// 获取等待通行的车辆数量
int getWaitingCount() {
return waitingCount.get();
}
}
// 车辆类
static class VehicleClass implements Runnable {
private Intersection intersection;
private int vehicleId;
VehicleClass(Intersection intersection, int vehicleId) {
this.intersection = intersection;
this.vehicleId = vehicleId;
}
@Override
public void run() {
while (!Thread.interrupted()) {
try {
Thread.sleep(1000); // 模拟车辆行驶时间
intersection.waitToPass(); // 车辆等待通行
System.out.println("Vehicle " + vehicleId + " passes the traffic light.");
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // 重新设置中断标志
}
}
}
}
}