1、Thread中的interrupt()对正在执行的线程有用吗?也就是假如在main中有下面代码段:
Thread t = new Thread(new MyRunnable());
t.start();//t的run方法只做一件事,不断的打印而已
t.interrupt();//这句对t起什么作用了吗?是不是将t的interrupted status设成true而已,根本没别的影响?2、能举例说明一下:一个线程t由于调用sleep、wait、join阻塞的时候,如果这时调用t.interrupt()会抛出InterruptedException,特别是wait和join的时候的情况3、Core Java有这样一句话:
However, if a thread is blocked, it cannot check the interrupted status. This is
where the InterruptedException comes in.?
为什么说InterruptedException  come in here呢?4、是不是只能interrupt(好像interrupt不一定中断一个线程)自己,其实就是下面这句是不是对的:
The current thread can only interrupt itself(稍微修改了文档上的一句话)

解决方案 »

  1.   

    http://blog.csdn.net/axman/archive/2005/12/26/562249.aspx
    这个应该可以解决你的问题
      

  2.   

    第一问你的理解是正确的,
    这个对于一个线程,仅仅是个标记,不会有其他的影响,但是当该线程正在
    wait,sleep,join的时候会抛出InterruptedException。
    另外,对于一个处于不活动状态的线程,你调用interrupt()没有任何影响。
      

  3.   

    第三问:
    当然一个线程对象可以通过调用interrupt设置中断标志,
    在其他的线程也可以通过对该线程的引用中断被引用的线程。
      

  4.   

    在main方法中(其他的线程)调用interruptpublic class Test extends Thread {
        private String name;
        
        public Test(String name) {
            this.name = name;
        }
        
        
        public static void main(String[]args) throws Exception{
            Thread  t1=new Test("myThread");
            t1.start();
            sleep(1000);
            t1.interrupt();    }
       
        public void run() {
                   while(true){
                    if(this.isInterrupted()){
                        System.out.println("exit*****************");
                        return;
                    }
                    System.out.println(name);        }
        }
        
    }
      

  5.   

    第二题的例子public class Test extends Thread {
        private String name;
        
        public Test(String name) {
            this.name = name;
        }
        
        
        public static void main(String[]args) throws Exception{
            Thread  t1=new Test("myThread");
            t1.start();
            sleep(1000);
            t1.interrupt();    }
       
        public synchronized void run(){
         try{
         wait();
         }catch(InterruptedException  e){
         e.printStackTrace();
         }
        
            
        }
        
    }
      

  6.   

    答:接ZiSheng兄弟贴子,基于上述贴子所述的原因,因此:一个线程要中止运行,必须时时注意检查"中断标记位",,当有别人中断它时,通常表明:可能别人要它停止运行了.
    线程是自己才能停止自己的运行.别人的interrupt()只是一种请求而已.
      

  7.   

    怎样理解"别人的interrupt()"呢?
    t.interrupt()不就是线程对象t将它start的线程的interrupted status设成true吗
    我认为无论如何,一个线程只能interrupt自己
    可能还有什么情况我没考虑到吧
    请大哥继续讲解一下
      

  8.   

    答:设有两个线程,一个是a,一个是t,当线程a在它的run(){...}代码中执行它自己的语句t.interrupt();时,含义是:线程a很可能希望线程t该中止运行了.即:线程a"中断"了线程t.