//连接Runable接口
public class Ticket implements Runnable{
//假设有100张票
static int Votes=100;
static Object obj=new Object();
@Override
public void run() {
//定义一个死循环
while (true){
//多个线程同时买票,保证不会卖出同一张票
synchronized (obj){
if (Votes>0){
System.out.println(Votes+"号票售出");
//卖出一张票票数--
Votes--;
}else {
System.out.println("票已售光.....");
//退出
System.exit(0);
}
}
}
}
public static void main(String[] args) {
//窗口1售票
Ticket ticket1 = new Ticket();
Thread thread1 = new Thread(ticket1);
thread1.start();
//窗口2售票
Ticket ticket2 = new Ticket();
Thread thread2 = new Thread(ticket1);
thread2.start();
//窗口3售票
Ticket ticket3 = new Ticket();
Thread thread3 = new Thread(ticket1);
thread3.start();
}
}
用多线程模拟三个窗口同时卖票
最新推荐文章于 2024-07-22 14:15:06 发布