I'm new to multithreading in java and I can't figure out on how to stop a thread.
I have an ArrayList
of threads which I want to stop.
Here is a snippet of my code:
class PrimeThread implements Runnable {
public void run() {
while(flag) {
//do some stuff
}
}
public void cancel() {
flag = false;
}
...
}
Class MainClass {
public static void stopPrimeThreads() {
for(int i=0; i<primeThreadList.size(); i++) primeThreadList.get(i).cancel();
}
}
I try to stop the thread by setting the flag
variable to false
. The flag
variable is a volatile boolean
declared in the class itself. I also tried to use an outer class variable as sentinel but that did not work either. Also a non volatile
variable does not do the job.
When I use the deprecated stop()
method I get the behavior I want, but I don't want to use a deprecated method.
Does anybody has an idea on how to fix this problem? Am I missing something fundamental?
Thanks in advance.
Make internal loop something like
while (flag) {
// smaller step 1
if (!flag) break;
// so on
}
As a side-note, if your internal loop takes very long time, it may indicate you using some sub-optimal algorithm. Though, if you working with very large numbers, long calculation times are unavoidable.