用java编程,模拟红绿灯,红灯亮10s,绿灯亮10s,黄灯亮2S
时间: 2024-12-23 08:26:54 浏览: 4
在Java编程中,我们可以创建一个简单的模拟红绿灯的程序,使用计时器和循环结构来控制信号灯的变化。这里是一个基本的示例:
```java
import java.util.Timer;
import java.util.TimerTask;
public class TrafficLight {
private int trafficSignalStatus; // 0 - 红灯,1 - 黄灯,2 - 绿灯
private static final int RED_LIGHT_SECONDS = 10;
private static final int GREEN_LIGHT_SECONDS = 10;
private static final int YELLOW_LIGHT_SECONDS = 2;
public void startSimulation() {
Timer timer = new Timer();
timer.schedule(new ChangeTrafficLightTask(), 0, 12000); // 每隔12000毫秒(即20秒)切换一次信号灯状态
}
private class ChangeTrafficLightTask extends TimerTask {
@Override
public void run() {
switch (trafficSignalStatus) {
case 0: // 红灯
System.out.println("红灯亮起,倒数 " + RED_LIGHT_SECONDS);
trafficSignalStatus = 1;
break;
case 1: // 黄灯
if (RED_LIGHT_SECONDS > 0) {
System.out.println("黄灯亮起,剩余 " + RED_LIGHT_SECONDS);
} else {
trafficSignalStatus = 2;
System.out.println("黄灯结束,转绿灯");
}
break;
case 2: // 绿灯
System.out.println("绿灯亮起,倒数 " + GREEN_LIGHT_SECONDS);
trafficSignalStatus = 0; // 到达绿灯后,重新回到红灯阶段
break;
}
RED_LIGHT_SECONDS--;
GREEN_LIGHT_SECONDS--;
}
}
public static void main(String[] args) {
TrafficLight trafficLight = new TrafficLight();
trafficLight.startSimulation();
}
}
阅读全文