用java多线程实现3. 在火车站,现有100位乘客在排队进站,这100位乘客按照从1到100的顺序依次编号。有三个进站口,这三个进站口依次编号为A口、B口、C口,每位乘客进站时间是1秒钟。
时间: 2024-03-21 13:42:33 浏览: 52
好的,您需要实现的是一个多线程的程序,用来模拟3个进站口同时接收100位乘客的情况。以下是一个可能的实现方式:
首先,定义一个 `Passenger` 类用来表示乘客,其中包含一个编号属性 `id`。然后,定义一个 `Station` 类表示火车站,其中包含一个 `passengerQueue` 队列,用来存储等待进站的乘客。另外,定义3个 `Gate` 类,分别表示A口、B口、C口。每个 `Gate` 类都有一个 `station` 属性,表示该口所属的火车站。在 `Gate` 类中,定义一个 `run` 方法,表示该进站口的工作流程。在该方法中,先定义一个 `while` 循环,用来不断地从 `station.passengerQueue` 中取出乘客,直到队列为空为止。在每次循环中,先判断当前是否有乘客在等待进站,如果有,则取出队首乘客,并将其进站时间设为1秒钟。为了模拟进站的时间,使用 `Thread.sleep(1000)` 方法来让当前线程休眠1秒钟。在乘客进站完成后,输出一条消息表示该乘客已经进站。最后,需要在主线程中创建3个 `Gate` 实例,并将它们分别启动,模拟3个进站口同时工作的情况。
代码如下:
```java
import java.util.LinkedList;
import java.util.Queue;
class Passenger {
public int id;
public Passenger(int id) {
this.id = id;
}
}
class Station {
public Queue<Passenger> passengerQueue = new LinkedList<>();
}
class Gate extends Thread {
public Station station;
public Gate(Station station) {
this.station = station;
}
@Override
public void run() {
while (true) {
synchronized (station.passengerQueue) {
if (!station.passengerQueue.isEmpty()) {
Passenger passenger = station.passengerQueue.poll();
passenger.id = this.getId();
System.out.println("Gate " + this.getId() + " is processing passenger " + passenger.id);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Passenger " + passenger.id + " has entered the station.");
}
}
}
}
}
public class Main {
public static void main(String[] args) {
Station station = new Station();
for (int i = 1; i <= 100; i++) {
station.passengerQueue.offer(new Passenger(i));
}
Gate gateA = new Gate(station);
Gate gateB = new Gate(station);
Gate gateC = new Gate(station);
gateA.start();
gateB.start();
gateC.start();
}
}
```
以上代码中,我们使用了 `synchronized` 关键字来保证同时只有一个进站口能够访问 `station.passengerQueue` 队列。同时,由于我们需要模拟多线程情况下的数据安全问题,因此在 `Passenger` 类中,我们将 `id` 属性设为 `public`,方便在多线程环境下对其进行修改。在实际开发过程中,为了避免数据安全问题,我们应该尽量避免在多线程中直接访问变量,而是通过加锁等方式来实现数据的安全访问。
相关推荐
![](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)
![](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)