java多线程模拟交通信号灯
时间: 2023-06-30 19:18:46 浏览: 59
好的,我可以为您提供一个简单的Java多线程模拟交通信号灯的示例代码。
```
public class TrafficSignal implements Runnable {
private String name;
private int greenTime; // 绿灯时间
private int yellowTime; // 黄灯时间
private int redTime; // 红灯时间
public TrafficSignal(String name, int greenTime, int yellowTime, int redTime) {
this.name = name;
this.greenTime = greenTime;
this.yellowTime = yellowTime;
this.redTime = redTime;
}
@Override
public void run() {
while (true) {
System.out.println(name + " 绿灯亮起");
try {
Thread.sleep(greenTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + " 黄灯亮起");
try {
Thread.sleep(yellowTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + " 红灯亮起");
try {
Thread.sleep(redTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
在这个示例中,我们定义了一个TrafficSignal类,它实现了Runnable接口。这个类有四个属性:name表示交通信号灯的名称,greenTime表示绿灯时间,yellowTime表示黄灯时间,redTime表示红灯时间。
在run()方法中,我们使用while循环模拟交通信号灯的不停循环。在循环中,我们依次输出绿灯、黄灯、红灯,并使用Thread.sleep()方法模拟灯亮起时间。
接下来,我们可以创建多个TrafficSignal对象,然后启动多个线程,来模拟多个交通信号灯。示例代码如下:
```
public class TestTrafficSignal {
public static void main(String[] args) {
TrafficSignal signal1 = new TrafficSignal("南北路口", 5000, 2000, 5000);
TrafficSignal signal2 = new TrafficSignal("东西路口", 3000, 1000, 3000);
Thread thread1 = new Thread(signal1);
Thread thread2 = new Thread(signal2);
thread1.start();
thread2.start();
}
}
```
在这个示例中,我们创建了两个TrafficSignal对象:南北路口和东西路口。然后,我们创建了两个Thread对象,并把TrafficSignal对象作为参数传递给它们。最后,我们启动了这两个线程,模拟了两个交通信号灯的运行。
希望这个简单的示例代码能够帮助您了解Java多线程模拟交通信号灯的实现方式。