multithreading - Thread Interruption in java -
i want clarification on thread interruption.
what if thread goes long time without invoking method throws aninterruptedexception? must periodically invoke thread.interrupted, returns true if interrupt has been received. example:
for (int = 0; < inputs.length; i++) { heavycrunch(inputs[i]); if (thread.interrupted()) { // we've been interrupted: no more crunching. return; } } when call method thread.interrupt() throws interrupted exception so, why need if (thread.interrupted())
try { (int = 0; < inputs.length; i++) { heavycrunch(inputs[i]); if (thread.interrupted()) { // we've been interrupted: no more crunching. return; } } } catch (interruptedexception ex) { ... }
when call thread.interrupt() on thread, 2 things happen:
- that thread's interrupt flag set.
- if thread blocked in method
throws interruptedexception, method throw exception immediately.
if thread busy in code not throw interruptedexception, won't exception. that's why you'd need check if (thread.interrupted()), check flag.
in sample code java compiler complain invalid catch block because none of code in try block throws interruptedexception.
Comments
Post a Comment