I want to stop a running thread immediately. Here is my code:
Class A :
public class A() {
public void methodA() {
For (int n=0;n<100;n++) {
//Do something recursive
}
//Another for-loop here
//A resursive method here
//Another for-loop here
finishingMethod();
}
}
Class B:
public class B() {
public void runEverything() {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
A a = new A();
a.methodA();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
My problem is that i need to be able to stop the thread in Class B even before the thread is finished. I’ve tried interrupt() method, but that doesn’t stop my thread. I’ve also heard about using shared variable as a signal to stop my thread, but I think with long recursive and for-loop in my process, shared-variable will not be effective.
Any idea ?
Thanks in advance.
Thread.interruptwill not stop your thread (unless it is in the sleep, in which case theInterruptedExceptionwill be thrown). Interrupting basically sends a message to the thread indicating it has been interrupted but it doesn’t cause a thread to stop immediately.When you have long looping operations, using a flag to check if the thread has been cancelled is a standard approach. Your
methodAcan be modified to add that flag, so something like:Then a cancel method can be added to set that flag
Then if someone calls
runEverythingonB,Bcan then just callcancelonA(you will have to extract theAvariable soBhas a reference to it even afterrunEverythingis called.