用JAVA写一个多线程抢票程序
时间: 2023-08-04 17:16:59 浏览: 144
12306抢票程序JAVA版.zip
好的,这是一个简单的多线程抢票程序,基于Java语言实现:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TicketBookingSystem {
public static void main(String[] args) {
// 假设有100张票需要抢购
int totalTicketNum = 100;
// 创建线程池
ExecutorService executorService = Executors.newFixedThreadPool(10);
// 模拟10个用户同时抢购
for (int i = 0; i < 10; i++) {
executorService.execute(new TicketBookingTask(i + 1, totalTicketNum));
}
// 关闭线程池
executorService.shutdown();
}
static class TicketBookingTask implements Runnable {
private int userId;
private int totalTicketNum;
public TicketBookingTask(int userId, int totalTicketNum) {
this.userId = userId;
this.totalTicketNum = totalTicketNum;
}
@Override
public void run() {
while (totalTicketNum > 0) {
synchronized (TicketBookingSystem.class) {
if (totalTicketNum > 0) {
System.out.println("用户" + userId + "抢到了第" + totalTicketNum + "张票");
totalTicketNum--;
} else {
System.out.println("用户" + userId + "没抢到票");
}
}
}
}
}
}
```
在这个程序中,我们使用了线程池来管理多个用户的抢票任务。每个任务都是一个实现了Runnable接口的内部类,通过共享totalTicketNum变量和synchronized关键字来保证线程安全。当totalTicketNum变量值为0时,用户就无法抢到票,程序输出"用户X没抢到票"。
阅读全文