从自身中断线程 [英] Interrupting a thread from itself

查看:57
本文介绍了从自身中断线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么线程在被自身中断时不抛出 InterruptedException .

I do not understand why the thread does not throw an InterruptedException when interrupted itself.

我正在尝试以下代码段:

I'm trying with following snippet:

公共类InterruptTest {

public class InterruptTest {

public static void main(String[] args) {
    MyThread t = new MyThread();
    t.start();
    try {
        t.join();
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
}

private static class MyThread extends Thread {

    @Override
    public void run() {
        Thread.currentThread().interrupt();
    }
} }

在API文档中,它在 interrupt()方法中说:

In the API docs it says on the interrupt() method:

如果调用Object类的wait(),wait(long)或wait(long,int)方法或Thread.join(),Thread.join(long)的方法阻塞了此线程,Thread.join(long,int),Thread.sleep(long)或Thread.sleep(long,int)这类方法,则其中断状态将被清除,并将收到InterruptedException.

If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the Thread.join(), Thread.join(long), Thread.join(long, int), Thread.sleep(long), or Thread.sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.

推荐答案

总是在其自己的线程上引发异常.您有两个不同的线程:主线程和创建的线程.在主线程中无法捕获MyThread中引发的异常.

Exceptions are always thrown on their own thread. You have two different threads: your main thread and the one you created. There's no way the exception thrown in MyThread can be caught in the main one.

这篇关于从自身中断线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆