黑马程序员技术交流社区

标题: 多线程的问题 [打印本页]

作者: 罗志辉    时间: 2015-10-17 12:52
标题: 多线程的问题
只要一用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. }
复制代码

作者: tianweidong    时间: 2015-10-17 15:13
我运行了一下正常啊,只是while没有跳出语句,不行的话你把sleep时间改长一点
作者: lkjmnbqwe    时间: 2015-10-17 22:03
这个好难看懂




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2