设计一个多线程程序,模拟火车售票窗口售票的功能。创建线程1和线程2,通过这两个线程共同售出100张票。 要求如下: (1)采用实现Runnable接口方式来创建多个线程; (2)要用同步代码块或同步方法来实现线程同步,解决存在的安全问题。java
时间: 2024-11-05 17:28:02 浏览: 3
java多线程之火车售票系统模拟实例
为了设计一个多线程程序模拟火车售票窗口售票功能,我们可以按照以下步骤操作:
1. 首先,创建一个`Ticket`类表示车票,包含车票ID和是否已售出的状态。
```java
public class Ticket {
private int id;
private boolean sold;
public Ticket(int id) {
this.id = id;
this.sold = false;
}
// getter and setter methods for id and sold status
public synchronized void sell() {
if (!sold) {
sold = true;
System.out.println("Ticket " + id + " has been sold.");
} else {
System.out.println("Ticket " + id + " is already sold.");
}
}
}
```
2. 创建一个`TrainCounter`类,实现`Runnable`接口,负责售出票务任务。我们将在其中维护一个`ArrayList<Ticket>`来存储可用的车票,并实现`run()`方法。
```java
import java.util.ArrayList;
import java.util.List;
public class TrainCounter implements Runnable {
private List<Ticket> tickets;
private final int totalTickets;
public TrainCounter(List<Ticket> tickets, int totalTickets) {
this.tickets = tickets;
this.totalTickets = totalTickets;
}
@Override
public void run() {
while (tickets.size() > 0) {
Ticket ticket = tickets.remove(0);
ticket.sell();
}
System.out.println("All tickets have been sold by both threads.");
}
}
```
3. 然后,创建两个`Thread`实例,每个代表一个售票窗口,分别将它们绑定到两个`TrainCounter`实例上。
```java
public class Main {
public static void main(String[] args) {
List<Ticket> tickets = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
tickets.add(new Ticket(i));
}
Thread thread1 = new Thread(new TrainCounter(tickets.subList(0, 50), 100));
Thread thread2 = new Thread(new TrainCounter(tickets.subList(50, 100), 100));
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
在这个例子中,我们使用了`synchronized`关键字来保护`sell()`方法,确保同一时刻只有一个线程能修改`sold`状态,防止数据竞争。我们还通过将售票任务分发给两个不同的`TrainCounter`实例实现了并发。
阅读全文