本帖最后由 李贺晓 于 2012-10-25 21:52 编辑  
 
class StopThread implements Runnable 
{ 
        private boolean flag =true; 
        public  synchronized void run() 
        { 
                while(flag) 
                { 
                        try 
                        { 
                                wait(); 
                        } 
                        catch (Exception e) 
                        { 
                                System.out.println(Thread.currentThread().getName()+"....Exception"); 
                        } 
                         
                        System.out.println(Thread.currentThread().getName()+"....run"); 
                } 
        } 
        public void changeFlag() 
        { 
                flag = false; 
        } 
} 
 
 
 
 
class  StopThreadDemo 
{ 
        public static void main(String[] args)  
        { 
                StopThread st = new StopThread(); 
                 
                Thread t1 = new Thread(st); 
                Thread t2 = new Thread(st); 
 
 
                t1.start(); 
                t2.start(); 
 
                int num = 0; 
 
                while(true) 
                { 
                        if(num++ == 60) 
                        { 
                                st.changeFlag(); 
                                break; 
                        } 
                        System.out.println(Thread.currentThread().getName()+"......."+num); 
                } 
                        } 
} 
这个时候当num=60的时候,把flag置为false后,线程不就进不去StopThread中的while中了,while不是都要判断,只要条件不符合,就不执行while中的内容,这个时候线程怎么会执行wait()呢,造成线程死锁,这个是什么原因 |