public class TextDemo {
public static void main(String[] args) {
TheRules theRules01=new TheRules(10);
ticketThread thd1=new ticketThread("窗口1:",theRules01,5);
ticketThread thd2=new ticketThread("窗口2:",theRules01,5);
ticketThread thd3=new ticketThread("窗口3:",theRules01,5);
thd1.start();
thd2.start();
thd3.start();
}
}
class TheRules{
Integer ticket;
public TheRules(Integer ticket) {
this.ticket = ticket;
}
public synchronized void rulesSyten(int myCount){
if(ticket==0){
System.out.println("票没了");
return;
}
if(myCount>ticket){
System.out.println("票量不足");
}else {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ticket=ticket-myCount;
System.out.println(Thread.currentThread().getName()+"售出"+myCount+"张票,剩余"+ticket);
}
}
}
class ticketThread extends Thread{
private TheRules theRules;
private int myCount;
public ticketThread(String name, TheRules theRules,int myCount) {
super(name);
this.theRules = theRules;
this.myCount=myCount;
}
@Override
public void run() {
theRules.rulesSyten(myCount);
}
}