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:

  1. that thread's interrupt flag set.
  2. 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

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -