I am trying to stop an executing runnable instance after the run method has been called.
I have come up with the below approach
public class StoppableWorkflowTask implements Runnable {
volatile Thread runner = null;
@Override
public void run() {
runner = Thread.currentThread();
try {
while (true) {
System.out.println("Stop Thread " + Thread.currentThread().getId());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
void stop() {
runner.stop();
}
}
public class StoppableWorkflowTaskTest {
public static void main(String[] args) {
StoppableWorkflowTask stoppableTask = new StoppableWorkflowTask();
Thread thread = new Thread(stoppableTask);
thread.start();
System.out.println(thread.currentThread().getId());
try {
stoppableTask.stop();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
As per Java documention it is unsafe to call thread.stop(). I have checked few examples , but all either use thread.sleep() which can be terminated on interrupt.