跟视频对比了好久,都运行不出视频的效果..
把tick设置成1000也只有Thread-0执行,求问什么原因.
- class Ticket implements Runnable
- {
- private int tick = 100;
- Object obj = new Object();
- boolean flag = true;
- public void run()
- {
- if(flag)
- {
- while(true)
- {
- synchronized(this)//把this改成obj能正常多线程执行.
- {
- if(tick>0)//把tick>0改成tick>90的话,前面是全Thread-0执行,后面全是Thread-1执行.
- {
- try{Thread.sleep(10);}catch (Exception e){}
- System.out.println(Thread.currentThread().getName()+".R-sale:"+tick--);
- }
- else
- break;
- }
- }
- }
- else
- while(true)
- {
- if(tick>0)
- show();
- else
- break;
- }
- }
- public synchronized void show()//this
- {
- if(tick>0)
- {
- try{Thread.sleep(10);}catch (Exception e){}
- System.out.println(Thread.currentThread().getName()+".S-sale:"+tick--);
- }
- }
- }
- class ThisLockDemo
- {
- 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();
- }
- }
复制代码 |
|