Java:当被另一个线程中断时,如何在线程上捕获InterruptedException? [英] Java: How do I catch InterruptedException on a thread, when interrupted by another thread?

查看:322
本文介绍了Java:当被另一个线程中断时,如何在线程上捕获InterruptedException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个多线程应用程序来连接外部服务器 - 每个都在不同的线程上 - 并且在有输入之前将被阻塞。其中每一个都扩展了Thread类。为了便于解释,我们称之为连接线程。

I'm developing a multithreaded application to make connections to external servers - each on separate threads - and will be blocked until there is input. Each of these extends the Thread class. For the sake of explanation, let's call these "connection threads".

所有这些连接线程都存储在并发hashmap中。

All these connection threads are stored in a concurrent hashmap.

然后,我允许RESTful Web服务方法调用取消任何线程。 (我正在使用Grizzly / Jersey,所以每次调用都是一个线程。)

Then, I allow RESTful web services method call to cancel any of the threads. (I'm using Grizzly/Jersey, so each call is a thread on its own.)

我检索特定的连接线程(来自hashmap)并调用中断()方法。

I retrieve the specific connection thread (from the hashmap) and call the interrupt() method on it.

所以,这是问题,在连接线程中,我如何捕获InterruptedException? (当外部RESTful命令停止连接线程时,我想做点什么。)

So, here is the question, within the connection thread, how do I catch the InterruptedException? (I'd like to do something when the connection thread is stopped by an external RESTful command.)

推荐答案


所以,这是一个问题,在连接线程中,如何捕获
的InterruptedException?

So, here is the question, within the connection thread, how do I catch the InterruptedException?

你不能。如果您的线程在读取I / O操作中被阻止,则它不能中断。这是因为中断只是设置一个标志来指示线程已被中断。但是如果你的线程已被I / O阻塞,它将看不到该标志。

正确的方法是关闭底层套接字(线程被阻塞),然后捕获异常并传播它。

因为你的连接线程扩展线程执行以下操作:

You can not. Since if your thread is blocked on a read I/O operation it can not be interrupted. This is because the interrupt just sets a flag to indicate that the thread has been interrupted. But if your thread has been blocked for I/O it will not see the flag.
The proper way for this is to close the underlying socket (that the thread is blocked to), then catch the exception and propagate it up.
So since your connection threads extend Thread do the following:

@Override  
public void interrupt(){  
   try{  
      socket.close();  
   }  
   finally{  
     super.interrupt();  
   }  
}   

这样就可以中断被阻塞的线程I / O.

This way it is possible to interrupt a thread blocked on the I/O.

然后在运行方法中执行:

@Override  
public void run(){  

    while(!Thread.currentThread().isInterrupted()){    
       //Do your work

    }  
}    

所以在你的情况下尝试 catch 一个 InterruptedException 。您无法中断I / O上阻塞的线程。只需检查您的线程是否已被中断,并通过关闭流来促进中断。

So in your case don't try to catch an InterruptedException. You can not interrupt the thread blocked on I/O. Just check if your thread has been interrupted and facilitate the interruption by closing the stream.

这篇关于Java:当被另一个线程中断时,如何在线程上捕获InterruptedException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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