java红绿灯简单代码
时间: 2024-06-30 11:01:00 浏览: 128
在Java中,我们可以使用多线程和控制台模拟一个简单的红绿灯交通信号灯系统。下面是一个简单的示例代码:
```java
public class TrafficLight {
private enum Light {RED, GREEN, YELLOW}
private Light currentLight = Light.RED;
private int lightDuration = 5; // 灯光持续时间(秒)
private final Object lock = new Object();
public void start() {
while (true) {
switch (currentLight) {
case RED:
turnGreen();
break;
case GREEN:
turnRed();
break;
case YELLOW:
System.out.println("Yellow light: Waiting for a moment...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
turnRed();
break;
}
synchronized (lock) {
try {
lock.wait(lightDuration * 1000); // 等待下一个灯周期
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private void turnGreen() {
System.out.println("Switching to green light.");
currentLight = Light.GREEN;
lock.notifyAll(); // 唤醒等待的线程
}
private void turnRed() {
System.out.println("Switching to red light.");
currentLight = Light.RED;
}
public static void main(String[] args) {
new TrafficLight().start();
}
}
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)