java - Any way to stop a thread that implements Runnable using a boolean , without extending Thread ? -
consider code :
public class mythread implements runnable{ private volatile static boolean running = true; public void stopthread() { running = false; } @override public void run() { while (running) { try { system.out.println("sleeping ..."); thread.sleep(15000); system.out.println("done sleeping ..."); } catch (interruptedexception e) { e.printstacktrace(); } } } public static void main(string[] args) { mythread thread = new mythread(); thread.run(); } }
is possible stop thread implements runnable boolean , without extending thread ?
is possible stop thread implements runnable
a class implements runnable
not thread. plain class no magic it, declaring single void run()
method. example therefore doesn't start threads.
so instead of misleadingly naming class mythread
, should name mytask
, pass thread
constructor:
final mytask task = new mytask(); new thread(task).start(); thread.sleep(2000); task.stoprunning(); // renamed stopthread
also, make running flag instance variable. each mytask
should have own running flag.
Comments
Post a Comment