java - call Thread.interrupt() but Thread is still working -
this question has answer here:
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)
, orwait(long, int)
methods of object class, or ofjoin()
,join(long)
,join(long, int)
,sleep(long)
, orsleep(long, int)
, methods of class, interrupt status cleared , receiveinterruptedexception
.
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
Post a Comment