java - Thread stop and synchronization -


i'm reading book says not use such code:

private volatile thread mythread;  ....  mythread.stop(); 

instead 1 should use:

if (mythread != null ) {   thread dummy = mythread;   mythread = null;   dummy.interrupt();   } 

unfortunately subject not elaborated further... explain me this?

everyone has given great information on why not call thread.stop().

sergey's comment fixed incorrect information gave interrupt() handling. prefer use signal flag, in lewap's answer. sergey's said, interrupt() purpose of waking thread that's in blocked operation. if thread doesn't call blocking operations, interrupt() won't terminate thread. thread though can call isinterrupted() see if interrupt has been called (a signal flag, basically).

going book's example, don't it.

if (mythread != null ) {      thread dummy = mythread;      mythread = null;      dummy.interrupt();  } 

there's no reason copy dummy variable in example. right confused.

the book authors might thinking trying prevent other threads simultaneously attempting interrupt same thread, interruption code not thread safe (the "check if null , set null" operation not atomic), writing dummy assignment muddying waters without adding actual thread safety.


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -