Java编写程序,请用java多线性方程实现20张票三个窗口按顺序依次卖票
时间: 2023-03-10 18:21:39 浏览: 88
我可以给你一个示例代码:public class TicketSeller {
public static void main(String[] args) {
int totalTickets = 20;
// 3 Windows
Object lock1 = new Object();
Object lock2 = new Object();
Object lock3 = new Object();
// Create 3 threads
Thread t1 = new Thread(new TicketSeller(totalTickets, lock1, lock2));
Thread t2 = new Thread(new TicketSeller(totalTickets, lock2, lock3));
Thread t3 = new Thread(new TicketSeller(totalTickets, lock3, lock1));
t1.start();
t2.start();
t3.start();
}
private int tickets;
private Object lockA, lockB;
public TicketSeller(int tickets, Object lockA, Object lockB) {
this.tickets = tickets;
this.lockA = lockA;
this.lockB = lockB;
}
public void run() {
while (true) {
synchronized (lockA) {
synchronized (lockB) {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + "卖出了第" + tickets-- + "张票");
} else {
break;
}
}
}
}
}
}
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)