class SellThread implements Runnable //程序有点小问题,当剩下最后一张票时,四个线程都运行,可能会出现票数为0,-1,-2。(系统长时间运行时)
//可加上一个静态方法sleep();它会抛出异常
{
int tickets=100;
//Object obj=new Object();//也可以声明一个Thread对象
Thread th=new Thread();
boolean b=false;
public void run()
{
if(b==false)
{
while(true)
sell();
}
else
{
while(true)
{ //同步方法利用的是this所代表的对象的锁
synchronized(this) //采用同步后,显示正确。此方法两步,1,声明Thread对象,2,用synchronized把原方法括起来
{ //这里换th为this
///*
if(tickets>0)
{
try
{
Thread.sleep(0);
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("th "+Thread.currentThread().getName()+" sell tickets:"+tickets);
tickets--;
}
//*/
}
}
}
}