简体   繁体   English

管理中断异常

[英]Managing InterruptedException

I have read http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html我已阅读http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html

I decide to make my lock uncancelable task by我决定通过以下方式使我的锁定不可取消任务

try {
    lockedRecords.wait();
} catch (InterruptedException e) {
    interrupted = true;
}

but is there a need to但是有没有必要

} finally {
    if (interrupted) {
        Thread.currentThread().interrupt();
    }
}

The article says that you should call interrupt() to preserve the interrupted status.文章说你应该调用 interrupt() 来保持中断状态。 I'm still very blur, so what if I set.interrupt?我还是很模糊,那么如果我 set.interrupt 呢? what happens next?接下来发生什么? a bit lost on this.. any input?对此有点迷失......任何输入?

What value does it bring to my program?它给我的程序带来什么价值? Please kindly explain in layman terms, greatly appreciated:D请用外行的方式解释,不胜感激:D

What's important here is the code that is not written in the example.这里重要的是示例中未编写的代码。 The method in the example ( getNextTask ) could be used in:示例中的方法 ( getNextTask ) 可用于:

while (!Thread.interrupted()) {
   Task task = getNextTask(queue);  
   doSomething(task);
}
System.out.println("The thread was interrupted while processing tasks.");
System.out.println("...stopped processing.");

The while loop above executes forever, unless someone interrupts the thread on which this loop runs.上面的while循环将永远执行,除非有人中断了运行此循环的线程。

If the interrupt status is not reset as is done in getNextTask however, when someone tries to interrupt the thread when the thread is in queue.take in getNextTask , then the interrupt is lost and the bit of code I wrote above will never stop looping.如果中断状态没有像在getNextTask中那样重置,但是当有人试图在线程处于 queue.take 中时中断线程时queue.take ,那么中断就会丢失,我上面写的getNextTask代码将永远不会停止循环。

The whole point of the example on the IBM webpage is that you must be very careful when you swallow an interrupt since it might accidentally make a thread impossible to interrupt. IBM 网页上示例的全部要点是,在吞下中断时必须非常小心,因为它可能会意外地使线程无法中断。

Just swallowing the InterruptedException is fine as long as you know that the current thread will terminate after your task is done and returns.只要您知道当前线程将在您的任务完成并返回后终止,只需吞下InterruptedException就可以了。

Problems may arise when using some thread pool, like ExecutorService , where usually the threads continue to run after a task has completed, waiting for the next task to come.使用某些线程池时可能会出现问题,例如ExecutorService ,通常线程在任务完成后继续运行,等待下一个任务的到来。 In this case the pooled thread should be notified it was interrupted so that it can do whatever is appropriate in this situation, eg perform a clean shutdown and exit.在这种情况下,应该通知池线程它已被中断,以便它可以在这种情况下执行任何适当的操作,例如执行干净的关闭和退出。

Thus, it is good practice and more safe to make sure you restore the interrupted state before returning from your routine.因此,在从例行程序返回之前,确保恢复中断的 state 是一种很好的做法,而且更安全。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM