Java编写程序,请用java多线性方程实现20张票三个窗口按顺序依次卖票
时间: 2023-03-10 19:21:39 浏览: 107
我可以给你一个示例代码: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;
}
}
}
}
}
}
阅读全文