class Example extends Thread {    volatile boolean stop = false;    public static void main(String args[]) throws Exception {        Example thread = new Example();        System.out.println("Starting thread...");        thread.start();        Thread.sleep(3000);        System.out.println("Asking thread to stop...");        thread.stop = true;    //(1)        Thread.sleep(3000);        System.out.println("Stopping application...");        System.exit(0);    }    public void run() {        while (!stop) {   //(2)            System.out.println("Thread is running...");            long time = System.currentTimeMillis();            while((System.currentTimeMillis() - time < 1000) && (!stop)) {            }        }        System.out.println("Thread exiting under request...");//(3)    }} 
在(1)中,把stop置为true 了后,确实可以不进入循环,但是这样线程真的中断了吗?只能说这个时候不进入(2)这个循环而已吧?其实run()这个方法应该还在运行中吧?也就是说这个线程没有真正意义上的中断。如果把(3)改成
        while(true){
      
            System.out.println("Thread exiting under request..."); //(4)
        
        }那还会继续执行(4)的代码,对不对?不知道我的理解是否正确,请各位大吓指正!

解决方案 »

  1.   

    run方法在出了while后,再运行第(3)句,然后就结束了啊
    这时线程也就结束了
    你可以这样看线程的状态。class Example extends Thread {    volatile boolean stop = false;    public static void main(String args[]) throws Exception {        Example thread = new Example();        System.out.println("Starting thread...");System.out.println("1"+thread.getState());
            thread.start();
            
    System.out.println("2"+thread.getState());
            Thread.sleep(3000);        System.out.println("Asking thread to stop...");System.out.println("3"+thread.getState());
            thread.stop = true;    //(1)System.out.println("4"+thread.getState());
            Thread.sleep(3000);System.out.println("5"+thread.getState());
            System.out.println("Stopping application...");
            
            System.exit(0);    }    public void run() {        while (!stop) {   //(2)            System.out.println("Thread is running...");            long time = System.currentTimeMillis();            while((System.currentTimeMillis() - time < 1000) && (!stop)) {            }        }        System.out.println("Thread exiting under request...");//(3)    }} 
      

  2.   

    thread.getState()是什么方法啊?
    还是没看出来
      

  3.   


    在(1)中,把stop置为true 了后,确实可以不进入循环,但是这样线程真的中断了吗?只能说这个时候不进入(2)这个循环而已吧?其实run()这个方法应该还在运行中吧?也就是说这个线程没有真正意义上的中断。
    ——————————————————————————————————————————
    当sotp设置成true以后就跳出while循环了。。然后执行输出语句。。执行完后线程结束
    如果把(3)改成
            while(true){
          
                System.out.println("Thread exiting under request..."); //(4)
            
            }那还会继续执行(4)的代码,对不对?
    ——————————————————————————————————————
    如果这样改线程就不会终止而是一直满足。。一直死循环了。。
      

  4.   

    线程离开了run方法意味着这个线程的终止。
    “没有任何语言方面的需求要求一个被中断的线程应该终止。
    中断一个线程只是为了引起该线程的注意 ,被中断线程可以决定如何应对中断。”这是core java2中的原话。