class TicketsSystem
{
public static void main(String[] args) throws Exception
{
TicketsThread tt=new TicketsThread();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
new Thread(tt).start();
}
}
class TicketsThread implements Runnable
{
int tickets=100;
public void run()
{ synchronized(this){
while(true)
{
try{
Thread.sleep(500);
} catch(InterruptedException e) {
}
if(tickets>0)
{
System.out.println(Thread.currentThread().getName()+" seil tickets: "+tickets);
tickets--;
}
if(tickets==5)
{
break;
}
}
}
}
}
因为第一个线程在tickets==5退出后,下一个线程继续tickets--,tickets再也不会变成5了。