本帖最后由 hdsjsql 于 2013-4-21 15:58 编辑
程序原本会死锁,注释掉try{Thread.sleep(10);}catch(Exception e){}则不会发生死锁.实在看不出这句代码对死锁有什么影响.运行过程中,ti,t2都以运行.- class Ticket implements Runnable
- {
-
- private static int tick = 1000;
- Object obj = new Object();
- boolean flag = true;
- public void run()
- {
- if(flag)
- {
- while(true)
- {
- synchronized(obj)
- {
-
- if(tick>0)
- {
- show();
- }
- }
- }
- }
- else
- while(true)
- show();
- }
- public synchronized void show()//this
- {
- synchronized(obj)
- {
- if(tick>0)
- {
- try{Thread.sleep(10);}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"....show.... : "+ tick--);
- }
- }
- }
- }
- public 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();
- }
- }
复制代码 |
|