之前对interrupt()方法一直不太理解,可能是这个名字太具有迷惑性了吧。

interrupt不能中断正在运行的线程,如下代码

class Example1 extends Thread {
    boolean stop = false;
    public static void main(String args[]) throws Exception {
        Example1 thread = new Example1();
        System.out.println("Starting thread...");
        thread.start();
        Thread.sleep(3000);
        System.out.println("Interrupting thread...");
        thread.interrupt();
        System.out.println("thread interrupt()" + thread.isInterrupted());
        Thread.sleep(3000);
        System.out.println("Stopping application...");
        // System.exit(0);
    }
    public void run() {
        while (!stop) {
            System.out.println("Thread is running...");
            long time = System.currentTimeMillis();
            while ((System.currentTimeMillis() - time < 1000)) {
            }
        }
        System.out.println("Thread exiting under request...");
    }
}

但是上面的代码还是有漏洞的,Example1对thread执行了interrupt操作,没有中断thread是因为interrupt方法只是在目标线程中设置了一个标志,表示它已经被中断。Example1对thread设置了中断标志但并没有检查这个标志是否被设置,所以Example1无法中断thread。对上面代码修改如下

class Example1 extends Thread {
    boolean stop = false;
    public static void main(String args[]) throws Exception {
        Example1 thread = new Example1();
        System.out.println("Starting thread...");
        thread.start();
        Thread.sleep(3000);
        System.out.println("Interrupting thread...");
        thread.interrupt();
        System.out.println("thread interrupt()" + thread.isInterrupted());
        Thread.sleep(3000);
        System.out.println("Stopping application...");
        // System.exit(0);
    }
    public void run() {
//检查中断标志
        while (!stop && !Thread.currentThread().isInterrupted()) {
            System.out.println("Thread is running...");
            long time = System.currentTimeMillis();
            while ((System.currentTimeMillis() - time < 1000)) {
            }
        }
        System.out.println("Thread exiting under request...");
    }
}