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

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -