美文网首页
InterruptedException异常

InterruptedException异常

作者: overflow_e4e4 | 来源:发表于2019-07-10 17:41 被阅读0次

总结了一下InterruptedException异常相关的信息。java中线程有一个终端状态,中断状态初始时为 false;当另一个线程通过调用Thread.interrupt() 中断一个线程时,会出现以下两种情况之一。如果那个线程在执行一个低级可中断阻塞方法,(例如 Thread.sleep()Thread.join()Object.wait()),那么它将取消阻塞并抛出InterruptedException。否则,interrupt() 只是设置线程的中断状态。 在被中断线程中运行的代码以后可以轮询中断状态,看看它是否被请求停止正在做的事情。中断状态可以通过 Thread.isInterrupted() 来读取,并且可以通过一个名为 Thread.interrupted() 的操作读取和清除。

如何实现一个可被强制停止的线程


package interrupt;

/**
 * 一个可停止的线程
 * @author xuecm
 */
public class InterruptedThread extends Thread {

    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            System.out.println("working");
        }

    }

    public static void main(String[] args) throws InterruptedException {

        InterruptedThread t = new InterruptedThread();
        t.start();
        Thread.sleep(2000);
        t.interrupt();
        System.out.println("thread t is stopped");


    }

}

输出结果

输出结果1.png

但是我们一般不这么写线程,我们一般会让线程sleep一小段时间,所以进一步修改。

package interrupt;

/**
 * 一个可停止的线程
 * @author xuecm
 */
public class InterruptedThread extends Thread {

    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            System.out.println("working");
            try {
                sleep(500);
            } catch (InterruptedException e) {
                interrupt();//注意:因为在捕捉到InterruptedException异常的时候就会自动的中断标志置为了false,

            }
        }

    }

    public static void main(String[] args) throws InterruptedException {

        InterruptedThread t = new InterruptedThread();
        t.start();
        Thread.sleep(2000);
        t.interrupt();
        System.out.println("thread t is stopped");


    }

}

为什么不用stop()

因为这个方法以及被弃用,我本人并没有怎么使用过这个方法,也没有踩过他的坑,总之别用就对了。
具体请看Thread之九:stop

其他参考文献:
https://www.cnblogs.com/canda/p/7835823.html
https://www.jianshu.com/p/a8abe097d4ed
https://www.ibm.com/developerworks/cn/java/j-jtp05236.html

相关文章

网友评论

      本文标题:InterruptedException异常

      本文链接:https://www.haomeiwen.com/subject/ilphkctx.html