class TestSYN2 {
public static void main(String[] agrs) throws Exception{
myrunable2 my2=new myrunable2();
Thread th1=new Thread(my2,"窗口1");
Thread th2=new Thread(my2,"窗口2");
Thread th3=new Thread(my2,"窗口3");
th1.start();
th2.start();
th3.start();
}
}
class myrunable2 implements Runnable{
int ticket=50;
int count = 0;
Object obj=new Object();
@Override
public void run() {
while(true){
synchronized(obj){
if(ticket<=0)
return;
else
{
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(count % 3 == 0 && Thread.currentThread().getName() == "窗口1"){
System.out.println(Thread.currentThread().getName()+":在售卖第"+ticket--+"票");
count ++;
}else if(count % 3 == 1 && Thread.currentThread().getName() == "窗口2"){
System.out.println(Thread.currentThread().getName()+":在售卖第"+ticket--+"票");
count ++;
}else if(count % 3 == 2 && Thread.currentThread().getName() == "窗口3"){
System.out.println(Thread.currentThread().getName()+":在售卖第"+ticket--+"票");
count ++;
}
}
obj.notify();
if(ticket<=0)
break;
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}