java - how to stop a thread in a threadpool -


i'm writing application spawns multiple concurrent tasks. i'm using thread pool implement that.

it may happen event occurs renders computations being done in tasks invalid. in case, stop running tasks, , start new ones.

my problem: how stop running tasks? solution implemented store reference task thread , call interrupt() on thread. in demo code:

public class task implements runnable {      private string name;     private thread runthread;      public task(string name) {         super();         this.name = name;     }      @override     public void run() {         runthread = thread.currentthread();          system.out.println("starting thread " + name);         while (true) {             try {                 thread.sleep(4000);                 system.out.println("hello thread " + name);             } catch (interruptedexception e) {                 // we've been interrupted: no more messages.                 return;             }         }     }      public void stop() {         runthread.interrupt();     }      public string getname() {         return name;     } } 

and main method is:

public static void main(string args[]) {     executorservice = executors.newfixedthreadpool(2);      task t1 = new task("task1");     task t2 = new task("task2");     executorservice.execute(t1);     executorservice.execute(t2);     executorservice.execute(new task("task3"));     executorservice.execute(new task("task4"));      try {         thread.sleep(12000);         t1.stop();         system.err.println("stopped thread " + t1.getname());         thread.sleep(8000);         t2.stop();         system.err.println("stopped thread " + t2.getname());     } catch (interruptedexception e) {         e.printstacktrace();     } } 

is solution, or there better way stop running thread in thread pool?

the idea behind approach 1 of several correct solutions. dealing interruptedexception gives great rundown on how should use interrupt mechanism. mechanism useful when long computations. 1 other thing keep in mind is possible other libraries spoil interrupt mechanism not doing guide says (not resetting interrupt state when haven't handled etc).

do note task class isn't thread-safe. stopping task before saving currentthread, give nullpointerexception.

a simpler approach set volatile boolean variable running , instead of while(true) loop doing while(running) approach (this more general).

another thing @ futuretask mechanism, has canceling mechanism uses interrupt mechanism.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -