本帖最后由 陈鹏 于 2013-6-19 23:40 编辑
- <div class="blockcode"><blockquote>class Ticket implements Runnable
- {
- private int tick = 300;
- Object obj = new Object();
- boolean flag = true;
- public void run()//就是这的问题把synchronized去掉就OK了
- {
- if(flag)
- {
- while(true)
- {
- synchronized(this)
- {
- if(tick>0)
- {
- try{Thread.sleep(10);}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"....sale : "+ tick--);
- }
- }
- }
- }
- else
- while (true)
- {
- show();
- }
- }
- public synchronized void show()
- {
- if(tick>0)
- {
- try{Thread.sleep(10);}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"----show : "+ 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();
- }
- }
- /*
- 为什么我的输出结果总是这个:
- Thread-0....sale : 20
- Thread-0....sale : 19
- Thread-0....sale : 18
- Thread-0....sale : 17
- Thread-0....sale : 16
- Thread-0....sale : 15
- Thread-0....sale : 14
- Thread-0....sale : 13
- Thread-0....sale : 12
- Thread-0....sale : 11
- Thread-0....sale : 10
- Thread-0....sale : 9
- Thread-0....sale : 8
- Thread-0....sale : 7
- Thread-0....sale : 6
- Thread-0....sale : 5
- Thread-0....sale : 4
- Thread-0....sale : 3
- Thread-0....sale : 2
- Thread-0....sale : 1
- 把ticket改成很大的数也是一样。
- 只能输出*sale : *的结果,而不能输出show的,
- 同样的代码毕老师的两种都能输出。
- 是电脑问题还是我这代码中有点不合理之处,求大伙帮忙解决,真的很急!!!!!!
- */
复制代码 |
|