编程技术网

关注微信公众号,定时推送前沿、专业、深度的编程技术资料。

 找回密码
 立即注册

QQ登录

只需一步,快速开始

从自身中断线程:Interrupting a thread from itself

speedogoo 线程 2022-5-13 10:37 29人围观

腾讯云服务器
从自身中断线程的处理方法

我不明白为什么线程在被自身中断时不抛出 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.

这篇关于从自身中断线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程技术网(www.editcode.net)!

腾讯云服务器 阿里云服务器
关注微信
^