package thread_;
public class TicketSystem {
public static void main(String[] args) {
// TicketSystem01 ticketSystem01 = new TicketSystem01();
// TicketSystem01 ticketSystem02 = new TicketSystem01();
// TicketSystem01 ticketSystem03 = new TicketSystem01();
// //出现票数超卖
// ticketSystem01.start();
// ticketSystem02.start();
// ticketSystem03.start();
//偶尔出现票数超卖,有隐患
TicketSystem02 ticketSystem02 = new TicketSystem02();
new Thread(ticketSystem02).start();//第一个线程
new Thread(ticketSystem02).start();//第二个线程
new Thread(ticketSystem02).start();//第三个线程
}
}
class TicketSystem01 extends Thread{
private static int ticketnum =100;//多个线程共享
@Override
public void run() {
while(true){
if (ticketnum<=0 ){//无票提示售罄
System.out.println("售罄");
break;
}
try {
Thread.sleep(50);//有票间隔售卖时间 50ms
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("窗口:"+Thread.currentThread().getName()+"售出一张票\t"+"还剩:"+(--ticketnum));
}
}
}
class TicketSystem02 implements Runnable{
private int ticketnum =100;//多个线程共享
@Override
public void run() {
while(true){
if (ticketnum<=0 ){//无票提示售罄
System.out.println("售罄");
break;
}
try {
Thread.sleep(50);//有票间隔售卖时间 50ms
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("窗口:"+Thread.currentThread().getName()+"售出一张票\t"+"还剩:"+(--ticketnum));
}
}
}
多线程售票系统模拟(实验证明其不足之处)
最新推荐文章于 2024-11-09 23:37:44 发布