I found this solution to know if a thread has been interrupted.
public class OurThread extends Thread(){
private volatile boolean stop = false;
public void run(){
while (!stop) {
//Do your actions
}
}
}
But my run method is only executed once, so It doesnt make sense to put it insisde a while loop. Another approach I found, is to check the Thread.isInterrupted() flag, and then terminate the thread. My run() method is pretty long so I would have to check lots of times this condition making my code dirty.
I have to apply this into four diferents processes so im trying to find a simpler, cleaner soution. I was hoping if is there something like:
try{//my code}
catch(interrumption)
The problem is that since my thread is interrumped by using future.cancel(), the interruption is not thrown inside my run() code, then i cant do that either.
Any suggestion?
By now im checking lots of times between the code if the thread has been cancelled.
Thanks 🙂
Firstly, don’t extend Thread, you should implement Runnable or Callable.
Secondly you can add a method like
and place this in the four places. This doesn’t add much code and isn’t as ugly as a task which won’t stop.