Why a thread would interrupt another thread [duplicate]

故事扮演 提交于 2019-12-23 16:44:56

问题


In Java multi threaded applications, we deal with InterruptedThreadException. This Exception is thrown if another thread interrupts the current thread. Now what is the reason another thread might want to interrupt the current thread when it knows that it is going to cause an Exception?


回答1:


Many reasons. But the most popular one is to cancel some task on a thread.

See http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html for details.




回答2:


In most cases, to notify that a Thread should abort. Usually, a worker thread executing some sort of batch operation is implemented in a way that it terminates itself (i.e. exit out of its run() method) when interrupted.

Unfortunately, a lot of programmers simply catch and swallow it which is a very very bad practice. If a Thread is not expecting an InterruptedException it should either re-throw or should restore its interrupted status if it cannot throw it (if restrained by an Interface for example) by calling

catch (InterruptedException e) {
    Thread.currentThread().interrupt();
}


来源:https://stackoverflow.com/questions/17494717/why-a-thread-would-interrupt-another-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!