期望运行结果是4个线程共享100张票,可实际运行结果为:买出的票远远大于100张(DOS命令行打印出101,102,....),更奇怪的是:将红色部分代码去掉,运行结果与期望相符,真是见了鬼了。。。
class MaiPiao implements Runnable
{
private int ticket=100;
public void run()
{
while(true)
{
if(ticket>0)
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"我要卖票"+ticket--);
}
}
}
class Class1
{
public static void main(String []args)
{
MaiPiao xc=new MaiPiao();
Thread t1=new Thread(xc);
Thread t2=new Thread(xc);
Thread t3=new Thread(xc);
Thread t4=new Thread(xc);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
[ 本帖最后由 troyli1986 于 2011-08-25 09:23 编辑 ] |