A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 罗志辉 中级黑马   /  2015-10-17 12:52  /  473 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

只要一用synchronized,就变成只有一个线程从头卖到尾,试验了数十遍了,怎么解决?
  1. class ThreadDemo3 implements Runnable
  2. {
  3.         private int ticket=5000;
  4.         String a=new String();
  5.         public void run()
  6.         {
  7.                 while(true)
  8.                 {
  9.                         synchronized(a)
  10.                         {
  11.                                 if(ticket>0)
  12.                                 {
  13.                                         try{Thread.sleep(5);} catch(Exception e){}
  14.                                         System.out.println(Thread.currentThread().getName()+"卖出了第"+(5000-(--ticket))+"张票!");
  15.                                 }
  16.                         }
  17.                 }
  18.         }
  19. }
  20. class ThreadTest3
  21. {
  22.         public static void main(String[] args)
  23.         {
  24.                 ThreadDemo3 r=new ThreadDemo3();
  25.                 Thread t0=new Thread(r,"售票窗口0");
  26.                 Thread t1=new Thread(r,"售票窗口1");
  27.                 Thread t2=new Thread(r,"售票窗口2");
  28.                 Thread t3=new Thread(r,"售票窗口3");
  29.                 /*
  30.                 Thread t4=new Thread(new Runnable()
  31.                 {
  32.                         private int cola=50;
  33.                         public void run()
  34.                         {
  35.                                 while(true)
  36.                                 {
  37.                                         if(cola>0)
  38.                                         {
  39.                                                 System.out.println(Thread.currentThread().getName()+"卖出了第"+(50-(--cola))+"杯可乐");
  40.                                         }
  41.                                 }
  42.                         }
  43.                 },"可乐窗口");*/
  44.                 t0.start();
  45.                 t1.start();
  46.                 t2.start();
  47.                 t3.start();
  48.                 //t4.start();
  49.         }
  50. }
复制代码

2 个回复

倒序浏览
我运行了一下正常啊,只是while没有跳出语句,不行的话你把sleep时间改长一点
回复 使用道具 举报
这个好难看懂
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马