顺序出现问题的原因??

qq_40740867 2017-11-22 05:42:55
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();
}
}
}
}
出现了这种情况

我知道是因为用的不是一个锁但是出现顺序错误的原理是啥??
...全文
75 回复 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

51,396

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧