java - Alternative method to kill thread -
i have been looking ways kill thread , appears popular approach
public class usingflagtoshutdownthread extends thread { private boolean running = true; public void run() { while (running) { system.out.print("."); system.out.flush(); try { thread.sleep(1000); } catch (interruptedexception ex) {} } system.out.println("shutting down thread"); } public void shutdown() { running = false; } public static void main(string[] args) throws interruptedexception { usingflagtoshutdownthread t = new usingflagtoshutdownthread(); t.start(); thread.sleep(5000); t.shutdown(); } }
however, if in while loop spawn another object gets populated data (say gui running , updating) how call - considering method might have been called several times have many threads while (running) changing flag 1 change everyone?
thanks
one approach these problems have monitor class handles threads. can start necessary threads (possibly @ different times/when necessary) , once want shutdown can call shutdown method there interrupt (or some) of threads.
also, calling thread
s interrupt()
method nicer approach out of blocking actions throw interruptedexception
(wait/sleep example). set flag there in threads (which can checked isinterrupted()
or checked , cleared interrupted()
. example following code can replace current code:
public class usingflagtoshutdownthread extends thread { public void run() { while (!isinterrupted()) { system.out.print("."); system.out.flush(); try { thread.sleep(1000); } catch (interruptedexception ex) { interrupt(); } } system.out.println("shutting down thread"); } public static void main(string[] args) throws interruptedexception { usingflagtoshutdownthread t = new usingflagtoshutdownthread(); t.start(); thread.sleep(5000); t.interrupt(); } }
Comments
Post a Comment