设计一个java程序,能够让多个用户同时从4个销售点完成100张票的购票操作。
时间: 2023-11-28 11:48:24 浏览: 34
这个问题可以通过使用多线程技术来解决。具体来说,我们可以定义一个“售票员”类,每个售票员代表一个销售点,该类实现了Runnable接口并包含一个run()方法,该方法模拟售票员的售票操作。然后我们创建四个售票员对象,每个对象代表一个销售点,然后将这些售票员对象作为参数传递给四个线程,以便每个线程代表一个销售点。
在主程序中,我们创建一个Ticket类,该类包含票的数量和一个sell()方法,该方法模拟售票员的售票操作。然后我们创建100个Ticket对象,每个对象代表一张票。在主程序中,我们创建四个线程对象,每个线程代表一个销售点,并在每个线程中调用售票员对象的run()方法。在每个线程中,每个售票员对象从Ticket对象中售出一张票,直到所有票都售完。
下面是一个简单的Java程序示例:
```java
class Ticket {
private int count = 100;
public synchronized void sell() {
if (count > 0) {
System.out.println(Thread.currentThread().getName() + " sells ticket " + count);
count--;
}
}
}
class TicketSeller implements Runnable {
private String name;
private Ticket ticket;
public TicketSeller(String name, Ticket ticket) {
this.name = name;
this.ticket = ticket;
}
public void run() {
while (true) {
ticket.sell();
try {
Thread.sleep(100); // 模拟售票员的售票操作
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
Ticket ticket = new Ticket();
Thread t1 = new Thread(new TicketSeller("Seller 1", ticket));
Thread t2 = new Thread(new TicketSeller("Seller 2", ticket));
Thread t3 = new Thread(new TicketSeller("Seller 3", ticket));
Thread t4 = new Thread(new TicketSeller("Seller 4", ticket));
t1.start();
t2.start();
t3.start();
t4.start();
}
}
```
在这个程序中,Ticket类包含了一个sell()方法,该方法使用synchronized关键字来确保线程安全。售票员类TicketSeller实现了Runnable接口并包含一个run()方法,该方法在循环中调用Ticket对象的sell()方法售出一张票,直到所有票都售完。在主程序中,我们创建了四个线程,每个线程代表一个销售点,并启动这些线程。当程序运行时,我们可以看到四个售票员对象同时从四个销售点售出100张票。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)