multithreading - Correct Way for Threads in Java -
i beginning learn threads in java , bit confused now. hope right place ask. made little program testing:
public class getinfo implements runnable { //private static boolean stoppointerinfo = false; private static thread tn; public static void startpointerinfo() { //stoppointerinfo = false; tn = new thread(new getinfo()); tn.start(); system.out.println("after start1"); } public static void stoppointerinfo() { //stoppointerinfo = true; tn.interrupt(); } @override public void run() { // while (stoppointerinfo == false) { while (! tn.isinterrupted() ) { try { thread.sleep(500); } catch (interruptedexception e) { tn.interrupt(); } . . dosomething } } }
because run()
method must know thread interrupted must use global definition of thread tn
?
should use interrupt()
method did or should use boolean variable in comments?
with method can't use interrupt
, must use boolean version because runnable r
doesn't know thread here?
public class getinfo { private static boolean stoppointerinfo = false; public static void startpointerinfo() { stoppointerinfo = false; getpointerinfo(); } public static void stoppointerinfo() { stoppointerinfo = true; } public static void getpointerinfo() { runnable r = new runnable() { @override public void run() { while (stoppointerinfo == false) { try { thread.sleep(500); } catch (interruptedexception e) { } . . dosomething } } }; new thread(r).start(); } }
the boolean flag solution fragile not guaranteed updates visible across different threads. fix problem may declare volatile, if set boolean flag don't interrupt sleep
call in first version. using interrupts preferred.
i see no reason declare thread tn
static. may use:
public class getinfo implements runnable { private final thread tn; private getinfo() { this.tn = new thread(this); this.tn.start(); } public static getinfo startpointerinfo() { getinfo info = new getinfo(); system.out.println("after start1"); return info; } public void stoppointerinfo() { tn.interrupt(); } ... }
and use this:
getinfo infoworker = getinfo.startpointerinfo(); ... infoworker.stoppointerinfo();
Comments
Post a Comment