我在 run()
中有一个与此类似的代码Runnable
的方法和那个 Runnable
的多个实例启动,
do{
try{
String contractNum=contractNums.take();
}catch(InterruptedException e){
logger.error(e.getMessage(), e);
}
}while(!("*".equals(contractNum)));
在哪里contractNums
是 BlockingQueue<String>
由多个线程共享。有单独的Runnables
将元素放入此队列。
我不确定抓到 InterruptedException
后的下一步,我应该通过重新抛出 RuntimeException
来终止这个线程吗? (所以我的 while
循环终止)或尝试从 contractNum queue
中获取下一个元素再次忽略InterruptedException
?
我不确定 InterruptedException
被视为线程终止或将其保留在 while 循环中的致命条件。
请推荐。
7.1.2 中断政策
Just as tasks should have a cancellation policy, threads should have
an interruption policy. An interruption policy determines how a thread
interprets an interruption request—what it does (if anything) when one
is detected, what units of work are considered atomic with respect to
interruption, and how quickly it reacts to interruption. The most
sensible interruption policy is some form of thread-level or service-
level cancellation: exit as quickly as practical, cleaning up if
necessary, and pos- sibly notifying some owning entity that the thread
is exiting. It is possible to establish other interruption policies,
such as pausing or resuming a service, but threads or thread pools
with nonstandard interruption policies may need to be restricted to
tasks that have been written with an awareness of the policy.
7.1.3 响应中断
As mentioned befor, when you call an interruptible blocking method
such as Thread.sleep or BlockingQueue.put , there are two practical
strategies for handling InterruptedException :
• Propagate the exception (possibly after some task-specific cleanup),
making your method an interruptible blocking method, too; or
• Restore the interruption status so that code higher up on the call
stack can deal with it.
Java Concurrency in Practice第 7 章。
特别是在您的代码中,您需要确保如果线程被中断,您的应用程序逻辑不会被破坏。
而且捕获你的中断异常确实更好。如何使用它取决于您,只需尝试确保您不会破坏应用程序逻辑即可。