java多线程电影院买票
时间: 2024-08-29 13:02:12 浏览: 61
在Java中,我们可以模拟一个多线程的电影院售票系统,通过创建多个线程来代表不同的购票操作。每个线程可能会代表一个用户尝试购买电影票。这里是一个简单的例子:
```java
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
class Ticket {
private int availableSeats = 50; // 假设初始座位数
private ReentrantLock lock = new ReentrantLock();
private Condition notFull = lock.newCondition();
public boolean buyTicket() {
lock.lock();
try {
if (availableSeats > 0) {
availableSeats--;
System.out.println(Thread.currentThread().getName() + " 购买了票,剩余:" + availableSeats);
notFull.signal(); // 售完票后通知其他等待者
return true;
} else {
System.out.println(Thread.currentThread().getName() + " 无法购票,已售罄");
return false;
}
} finally {
lock.unlock();
}
}
// 当所有票卖完后,唤醒所有等待在notFull条件下的线程
public void notifyAllWhenEmpty() {
while (availableSeats == 0 && !notFull.isSignaled()) {
notFull.await();
}
}
}
public class MovieTheater {
private final Ticket ticket;
public MovieTheater(int initialSeats) {
this.ticket = new Ticket();
ticket.setAvailableSeats(initialSeats); // 初始化座位
}
public void sellTickets(int numTickets) {
Thread[] buyers = new Thread[numTickets];
for (int i = 0; i < numTickets; i++) {
buyers[i] = new Thread(() -> {
boolean success = ticket.buyTicket();
if (!success) {
System.out.println(Thread.currentThread().getName() + " 抢购失败");
}
});
buyers[i].start();
}
}
}
public class Main {
public static void main(String[] args) {
MovieTheater theater = new MovieTheater(50); // 创建电影院实例
theater.sellTickets(10); // 启动10个购票线程
}
}
```
在这个示例中,`MovieTheater`类负责创建和管理电影院,而每个购票线程会在`sellTickets`方法中竞争购买票。`ReentrantLock`和`Condition`用于同步多个线程对售票操作的访问,避免了并发修改数据带来的问题。
阅读全文