三个人排队买票的多线程问题

liuzheng_jz 2014-03-11 04:54:58
程序运行结果只打印了“张某拿20,找15,给其放场券”为什么其它两个线程没有运行或是没有被唤醒呢?

public class TicketsTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
//启动三个买票线程
new Thread(new ZhangShanThread(new Tickets())).start();
new Thread(new LisiThread(new Tickets())).start();
new Thread(new ZhaoliuThread(new Tickets())).start();
}

}

public class Tickets {
private int Tickets=1;

public synchronized void zhangshan()
{
if(Tickets==3||Tickets==2)
{
try{
wait();
}catch(InterruptedException e){}

}
System.out.println("张某拿20,找15,给其放场券");
Tickets++;
notify();
}

public synchronized void lisi()
{
if(Tickets==3||Tickets==1)
{
try{
wait();
}catch(InterruptedException e){}

}
System.out.println("李某拿15找回10块,给其放场券");
Tickets++;
notify();
}

public synchronized void zhaoliu()
{
if(Tickets==1||Tickets==2)
{
try{
wait();
}catch(InterruptedException e){}

}
System.out.println("赵某5块刚好,给其放场券");
//Tickets++;
notify();
}
}
//三个线程
public class ZhangShanThread implements Runnable {
private Tickets t=null;
public ZhangShanThread(Tickets t)
{
this.t=t;
}
public void run()
{
t.zhangshan();
}
}
public class LisiThread implements Runnable {
private Tickets t=null;
public LisiThread(Tickets t)
{
this.t=t;
}
public void run()
{
t.lisi();
}
}
public class ZhaoliuThread implements Runnable {
private Tickets t=null;
public ZhaoliuThread(Tickets t)
{
this.t=t;
}
public void run()
{
t.zhaoliu();
}
}
...全文
948 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
liuzheng_jz 2014-03-11
  • 打赏
  • 举报
回复
恍然大悟呀!!!!!!
java_liyi 2014-03-11
  • 打赏
  • 举报
回复
又见new Tickets这种写法,锁之所以有用针对的是同一个资源,你所有Thread里面都去new Tickets这有什么用?

51,396

社区成员

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

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