用java编写一个程序模拟多个售票窗口售卖一列火车票的过程。具体的,共有10个售票窗口,每个售票窗口随机休眠一段时间后售出随机数量的车票(1~10张);每张车票有唯一的编号(例如:1~1000号);请使用同步机制确保同一编号的一张票只能被售卖一次;该列车票售卖完毕,程序运行结束。 提示:可设定程序中按顺序售卖车票;请使用同步机制确保程序运行正确。
时间: 2023-06-16 15:06:32 浏览: 139
下面是一个可能的Java程序实现:
```java
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class TrainTicketSellingSimulation {
private static final int NUM_WINDOWS = 10;
private static final int NUM_TICKETS = 1000;
private static final int TICKETS_PER_WINDOW = NUM_TICKETS / NUM_WINDOWS;
private static Set<Integer> soldTicketIds = new HashSet<>();
public static void main(String[] args) throws InterruptedException {
Thread[] windows = new Thread[NUM_WINDOWS];
for (int i = 0; i < NUM_WINDOWS; i++) {
int from = i * TICKETS_PER_WINDOW + 1;
int to = (i + 1) * TICKETS_PER_WINDOW;
windows[i] = new Thread(new TicketSeller(from, to));
windows[i].start();
}
for (int i = 0; i < NUM_WINDOWS; i++) {
windows[i].join();
}
System.out.println("All tickets have been sold.");
}
private static class TicketSeller implements Runnable {
private int from;
private int to;
private Random random = new Random();
public TicketSeller(int from, int to) {
this.from = from;
this.to = to;
}
@Override
public void run() {
for (int i = from; i <= to; i++) {
try {
Thread.sleep(random.nextInt(500)); // simulate selling time
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (soldTicketIds) {
while (soldTicketIds.contains(i)) { // wait for other threads to sell this ticket
try {
soldTicketIds.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
soldTicketIds.add(i);
System.out.println("Ticket " + i + " is sold by window " + Thread.currentThread().getId());
soldTicketIds.notifyAll(); // notify other threads that this ticket is sold
}
}
}
}
}
```
该程序使用了10个线程模拟10个售票窗口,每个窗口售卖一定范围内的车票。为了确保同一编号的车票只被售卖一次,使用了同步机制(`synchronized`),即对售出的车票编号进行互斥访问。具体来说,每当一个窗口售出一张车票,它会先检查该车票是否已经被售出,如果已经被售出,则该窗口线程会等待其他线程售卖完该车票后再重新尝试售卖。这里使用了Java的`wait()`和`notifyAll()`方法来实现等待和唤醒操作。当一个窗口售出一张车票后,它会通知其他等待售卖该车票的窗口线程,然后释放该车票编号的锁。这样可以确保同一编号的车票只被售卖一次,程序运行正确。
阅读全文