java - call Thread.interrupt() but Thread is still working -


java code:

public class test {     public static void main(string[] args) throws interruptedexception {         customer customer = new customer();         customer.start();  // start customer         thread.sleep(5000);         customer.interrupt();  // interrupt     }  }  class customer extends thread {      @override     public void run() {         while (!thread.currentthread().isinterrupted()) {              system.out.println("test interrupted +++++");             try {                 thread.sleep(500);             } catch (interruptedexception e) {                 e.printstacktrace();             }         }     }  } 

i call customer.interrupt() customer still working;
console result:

test interrupted +++++ .... test interrupted +++++ java.lang.interruptedexception: sleep interrupted test interrupted +++++     @ java.lang.thread.sleep(native method)     @ com.yitai.common.redisqueue.customer.run(test.java:22) test interrupted +++++ test interrupted +++++ ....  //more 

if change code in way : add thread.currentthread().interrupt() in catch

try {     thread.sleep(500); } catch (interruptedexception e) {     thread.currentthread().interrupt();  // add     e.printstacktrace(); } 

customer stoped why?
console result:

test interrupted +++++ ....  test interrupted +++++ java.lang.interruptedexception: sleep interrupted     @ java.lang.thread.sleep(native method)     @ com.yitai.common.redisqueue.customer.run(test.java:22) // end 

what happening calling thread.interrupt() clears thread's interrupted status if thread waiting, causing loop continue. javadoc (my emphasis):

if thread blocked in invocation of wait(), wait(long), or wait(long, int) methods of object class, or of join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of class, interrupt status cleared , receive interruptedexception.

to put way, if possible thread receive interruptedexception (because in wait state) exception sent , interrupt status cleared. interrupt status set when not possible synchronously deliver exception.

you need account in program's logic terminating thread, assuming intention. need correctly handle both possibilities.


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -