首页 > 其他 > 详细

interrupt()理解

时间:2014-04-13 05:04:16      阅读:454      评论:0      收藏:0      [点我收藏+]

之前对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...");
    }
}


本文出自 “混混” 博客,请务必保留此出处http://yimaoqian.blog.51cto.com/1328422/1394626

interrupt()理解,布布扣,bubuko.com

interrupt()理解

原文:http://yimaoqian.blog.51cto.com/1328422/1394626

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!