设计一个java程序,能够让多个用户同时从4个销售点完成100张票的购票操作。
时间: 2023-12-10 07:39:57 浏览: 36
这个问题涉及到多线程编程和同步问题,可以采用Java的并发包来实现。以下是一个基本的程序框架:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TicketSellingSystem {
public static void main(String[] args) {
// 创建销售点
TicketBox[] ticketBoxes = new TicketBox[4];
for (int i = 0; i < 4; i++) {
ticketBoxes[i] = new TicketBox(i + 1, 100);
}
// 创建线程池
ExecutorService executorService = Executors.newFixedThreadPool(10);
// 创建用户购票任务
for (int i = 1; i <= 10; i++) {
executorService.execute(new User(i, ticketBoxes));
}
// 关闭线程池
executorService.shutdown();
}
}
class User implements Runnable {
private int id;
private TicketBox[] ticketBoxes;
public User(int id, TicketBox[] ticketBoxes) {
this.id = id;
this.ticketBoxes = ticketBoxes;
}
@Override
public void run() {
// 随机选择一个销售点购票
int index = (int) (Math.random() * ticketBoxes.length);
TicketBox ticketBox = ticketBoxes[index];
// 购买1张票
if (ticketBox.sell(1)) {
System.out.println("User " + id + " bought 1 ticket from TicketBox " + ticketBox.getId());
} else {
System.out.println("User " + id + " failed to buy ticket from TicketBox " + ticketBox.getId());
}
}
}
class TicketBox {
private int id;
private int total;
private int sold;
public TicketBox(int id, int total) {
this.id = id;
this.total = total;
this.sold = 0;
}
public synchronized boolean sell(int count) {
if (sold + count > total) {
return false;
}
sold += count;
return true;
}
public int getId() {
return id;
}
}
```
程序中创建了4个销售点(`TicketBox`对象),每个销售点都有100张票。创建了10个用户(`User`对象),每个用户随机选择一个销售点进行购票操作。购票操作使用`synchronized`关键字进行同步,确保多个用户不会同时购买同一张票。最后,使用线程池来管理并发任务,确保多个用户同时购票。