interrupt, isInterrupted, interrupted

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了interrupt, isInterrupted, interrupted相关的知识,希望对你有一定的参考价值。

interrupt, isInterrupted, interrupted

今天学习了java多线程中的终止线程的相关知识, 稍微了解了下用法, 这里记录一下.

1.interrupt

通常情况, 我们不应该使用stop方法来终止线程, 而应该使用interrupt方法来终止线程. 看代码:

package com.bao.bao;


/**
 * Created by xinfengyao on 16-3-29.
 */
public class ThreadDemo1 extends Thread {
    boolean stop = false;
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new ThreadDemo1(), "my thread");
        System.out.println("starting thread...");
        thread.start();
        Thread.sleep(3000);
        System.out.println("interrupting thread...");
        thread.interrupt();
        System.out.println("线程是否中断:" + thread.isInterrupted());
        Thread.sleep(3000);
        System.out.println("stopping application");
    }
    @Override
    public void run() {
        while (!stop) {
            System.out.println("my thread is running...");
            long time = System.currentTimeMillis();
            while (System.currentTimeMillis() - time < 1000) {}
        }
        System.out.println("my thread exiting under request...");
    }
}

运行结果:

starting thread...
my thread is running...
my thread is running...
my thread is running...
interrupting thread...
线程是否中断:true
my thread is running...
my thread is running...
my thread is running...
stopping application
my thread is running...
my thread is running...
my thread is running...
my thread is running...
........

咦? 运行结果明明看到了线程是已经中断了的, 为什么还是一直在运行呢? 难道interrupt()方法有问题? 下面是我看别人博客了解到的知识:

实际上, 在java api文档中对该方法进行了详细的说明. interrupt方法并没有实际中断线程的执行, 只是设置了一个中断状态, 当该线程由于下列原因而受阻时, 这个中断状态就起作用了.

(1)如果线程在调用了Object类的 wait()、wait(long) 或 wait(long, int) 方法,或者该类的 join()、join(long)、join(long, int)、sleep(long) 或 sleep(long,

int) 方法过程中受阻,则其中断状态将被清除,它还将收到一个InterruptedException异常。这个时候,我们可以通过捕获 InterruptedException异常来

终止线程的执行,具体可以通过return等退出或改变共享变量的值使其退出.

(2)如果该线程在可中断的通道上的 I/O 操作中受阻,则该通道将被关闭,该线程的中断状态将被设置并且该线程将收到一个

ClosedByInterruptException。这时候处理方法一样,只是捕获的异常不一样而已。

 

以上是关于interrupt, isInterrupted, interrupted的主要内容,如果未能解决你的问题,请参考以下文章

interrupted()和isInterrupted()比较

关于Java多线程-interrupt()interrupted()isInterrupted()解释

java interrupted与isInterrupted方法

关于线程 interrupt

interrupt interrupted isInterrupted 区别

interrupt ,interrupted 和 isInterrupted