public class Maipiao {
public static void main(String[] args){
String s1="张三",s2="孙大明",s3="赵忠堂",s4="李四",s5="王二";
new Cinema(s1,5,1).start();
new Cinema(s2,20,2).start();
new Cinema(s3,10,3).start();
new Cinema(s4,10,4).start();
new Cinema(s5,5,5).start();
}
}
class Cinema extends Thread{
Ticketseller seller;
public String name;
int remoney;
int number;
Cinema(String s,int money,int i){
seller=new Ticketseller();
this.name=s;
this.remoney=money;
this.number=i;
}
public void run(){
seller.sellTicket(remoney,name);
}
}
class Ticketseller{
int fivenumber=1,tennumber=0,twentynumber=0;
public synchronized void sellTicket(int receivemoney,String name){
if(receivemoney==5){
fivenumber=fivenumber+1;
System.out.println(name+"给售票员5元钱,售票员卖给"+name+"一张票,不必找赎");
}
else if(receivemoney==10){
while(fivenumber<1){
try{
System.out.println(name+"给售票员10元钱");
System.out.println("售票员请"+name+"靠边等一会");
wait();
System.out.println(name+"结束等待,继续买票");
}
catch (InterruptedException e){}
}
fivenumber=fivenumber-1;
tennumber=tennumber+1;
System.out.println(name+"给售票员10元钱,售票员卖给"+name+"一张票,找赎5元");
}
else if(receivemoney==20){
while(fivenumber!=3&(fivenumber<1||tennumber<1)){
try{
System.out.println(name+"给售票员20元钱");
System.out.println("售票员请"+name+"靠边等一会");
wait();
System.out.println(name+"结束等待,继续买票");
}
catch (InterruptedException e){}
}
fivenumber=fivenumber-1;
tennumber=tennumber-1;
twentynumber=twentynumber+1;
System.out.println(name+"给售票员20元钱,售票员卖给"+name+"一张票,找赎15元");
}
notifyAll();
}
}
售票排隊
最新推荐文章于 2023-07-26 20:37:27 发布