线程 interrupt() 中断

2019-05-11  本文已影响0人  gczxbb

一、正常运行状态的线程 interrupt() 中断

Thread 类 interrupt() 方法,一个线程正常运行时(非休眠),调用线程对象 interrupt() 方法,线程执行既不会停止,也不会抛出异常,仅设置一个中断标志,线程继续执行,直到遇到休眠时,抛出异常。

final Thread thread = new Thread(new Runnable() {

    @Override
    public void run() {
        try {
            while (true) {
                System.out.println("thread running loop");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("thread end!");
    }
});
thread.start();
try {
    Thread.sleep(2000);
} catch (Exception e) {
    e.printStackTrace();
}
thread.interrupt();

一个 while 循环线程,主线程调用 Thread 对象 interrupt() 方法时,System 打印未停止,说明线程执行未受到影响。

添加判断条件成 isInterrupted() 方法。

while (!Thread.currentThread().isInterrupted()) {
    System.out.println("thread running loop");
}

一旦 interrupt() 被中断,线程执行结束。

二、休眠状态的线程 interrupt() 中断

线程正在 休眠阻塞 sleep() 方法,调用线程对象 interrupt() 方法,抛出异常,进入 InterruptedException 代码块执行。

final Thread thread = new Thread(new Runnable() {

    @Override
    public void run() {
        try {
            while(true) {
                Thread.sleep(10000);
            }
        } catch (Exception e) {
            System.out.println("thread exception!");
            e.printStackTrace();
        }
        System.out.println("thread end!");
    }
});
thread.start();
try {
    Thread.sleep(2000);
} catch (Exception e) {
    e.printStackTrace();
}
thread.interrupt();

主线程调用 Thread 对象的 interrupt() 方法,线程捕获到中断,立即抛出异常,结束线程。
wait() 方法休眠,同样会抛出 InterruptedException 异常。

三、Thread 的 interrupted 中断状态

Thread 类的 interrupted() 方法,检查当前线程中断状态,静态类方法,仅获取调用他的线程的中断状态,不在特定的线程对象中使用。

final Thread thread = new Thread(new Runnable() {

    @Override
    public void run() {
        try {
             while (!Thread.interrupted()) {
                    System.out.println("thread running loop");
             }
             System.out.println(Thread.interrupted());
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("thread end!");
        }
    });
    thread.start();
    try {
        Thread.sleep(2000);
    } catch (Exception e) {
        e.printStackTrace();
    }
    thread.interrupt();
}

线程对象调用 interrupt() 方法,设置线程中断标志,interrupted() 方法查询,退出循环。

退出后,再次打印 interrupted() 方法返回值,结果是 无中断标志。说明调用 interrupted() 方法后,自动重置中断状态。

线程对象的 isInterrupted() 方法 查询,结果未 重置中断状态,这就是二者的区别。


任重而道远

上一篇 下一篇

猜你喜欢

热点阅读