class Demo
{
public static void main(String[] args)
{
Ticket t=new Ticket();
Thread t1=new Thread(t);
Thread t2=new Thread(t);
t1.start();
try{Thread.sleep(10);}catch(Exception e){}
t.flag=false;
t2.start();
}
}
class Ticket implements Runnable
{ Object o=new Object();
private int num=100;
boolean flag=true;
public synchronized void show(){if(num>0){
System.out.println("售票台"+Thread.currentThread().getName()+"...sale1..."+num--);
}
}
public void run(){
if(flag){
while(true){
synchronized(o){
if(num>0){
System.out.println("售票台"+Thread.currentThread().getName()+"...sale2..."+num--);
}
}
}
}else{ while(true){
this.show();
}
}
}
}
会出现这种问题!我知道是因为用的不是一个锁,但我想知道的是因为用的不是一个锁,线程在执行时候出现了什么错误,导致了这种结果
这个你觉得哪里错了呢, 不正好是在交替卖票么
这运行的不是好好的嘛。。。哪里出错了。。。。。。
你的问题是不是数字不是连续的,这是正常的