只要一用synchronized,就变成只有一个线程从头卖到尾,试验了数十遍了,怎么解决?
- class ThreadDemo3 implements Runnable
- {
- private int ticket=5000;
- String a=new String();
- public void run()
- {
- while(true)
- {
- synchronized(a)
- {
- if(ticket>0)
- {
- try{Thread.sleep(5);} catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"卖出了第"+(5000-(--ticket))+"张票!");
- }
- }
- }
- }
- }
- class ThreadTest3
- {
- public static void main(String[] args)
- {
- ThreadDemo3 r=new ThreadDemo3();
- Thread t0=new Thread(r,"售票窗口0");
- Thread t1=new Thread(r,"售票窗口1");
- Thread t2=new Thread(r,"售票窗口2");
- Thread t3=new Thread(r,"售票窗口3");
- /*
- Thread t4=new Thread(new Runnable()
- {
- private int cola=50;
- public void run()
- {
- while(true)
- {
- if(cola>0)
- {
- System.out.println(Thread.currentThread().getName()+"卖出了第"+(50-(--cola))+"杯可乐");
- }
- }
- }
- },"可乐窗口");*/
- t0.start();
- t1.start();
- t2.start();
- t3.start();
- //t4.start();
- }
- }
复制代码 |
|