I am writing an application that spawns several simultaneous tasks. I use a thread pool to implement this.
It may happen that an event occurs that makes the calculations performed in tasks invalid. In this case, I would like to stop the current tasks and start new ones.
My problem: how to stop current tasks? The solution I implemented is to keep a reference to the task thread and call interrupt() on that thread. In the 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 from thread " + name); } catch (InterruptedException e) {
And the main method:
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 this a good solution, or is there a better way to stop the current thread in the thread pool?
java
user456045
source share