使用Java,模拟红绿灯,红灯亮10s,绿灯亮10s,黄灯亮2S.
时间: 2024-12-24 08:16:48 浏览: 7
在Java中,我们可以创建一个简单的红绿灯模拟程序,使用类和定时器来控制灯的状态变化。下面是一个简单的例子:
```java
import java.util.concurrent.TimeUnit;
class TrafficLight {
private enum Light {RED, GREEN, YELLOW}
private Light currentLight = Light.RED;
private int greenDuration = 10;
private int yellowDuration = 2;
private int redDuration = 10;
public void start() {
while (true) {
switch (currentLight) {
case RED:
System.out.println("红灯亮");
Thread.sleep(redDuration * 1000);
currentLight = Light.YELLOW;
break;
case YELLOW:
System.out.println("黄灯亮");
Thread.sleep(yellowDuration * 1000);
currentLight = Light.GREEN;
break;
case GREEN:
System.out.println("绿灯亮");
Thread.sleep(greenDuration * 1000);
break;
}
}
}
// 如果需要暂停或停止,可以添加相应的方法
}
public class Main {
public static void main(String[] args) {
TrafficLight trafficLight = new TrafficLight();
trafficLight.start();
}
}
```
在这个示例中,我们定义了一个`TrafficLight`类,其中包含三种灯光状态:`RED`、`GREEN`和`YELLOW`。每个颜色都有对应的持续时间。程序会无限循环地切换这三种颜色,每次切换之间有相应的延迟。
阅读全文