I’ve written the class VideoProcessor, which does some heavy processing on a video. If “started”, a new Thread is created and the reference is saved in the field videoProcessingThread. The problem now is:
videoProcessingThread.interrupt();
This does not seem to have any effect, as isInterrupted() never evaluates to true. I also added other interrupt checks, just to be sure; but they don’t “work” either. I’ve implemented a workaround:
videoProcessingThread.kill();
This seems to actually “kill” the thread. The method kill sets the boolean variable kill to true and that is evaluated correctly and the Thread returns.
videoProcessingThread = new Thread() {
boolean kill = false; // workaround
public void run() {
// init stuff
while (currentFrameIndex < totalFrames) {
if (isInterrupted()) {
System.out.println("isInterrupted");
return;
}
if (Thread.interrupted()) {
System.out.println("interrupted");
return;
}
if (Thread.currentThread().isInterrupted()) {
System.out.println("Thread.currentThread().isInterrupted()");
return;
}
if (kill) {
System.out.println("killed");
return;
}
}
// heavy processing
}
public void kill() {
kill = true;
}
}
What am I doing wrong?
First of all, calling
interrupt()may not actually set the interrupted status, please see here in javadocs the exact conditions, sometimes it will just throw anInterruptedException.Second, actually calling the
interrupted()method will also clear the interrupted status in addition to returning it, so the next call toisInterrupted()(which only returns the current status, but does not clear it) may not do what you expect.Using a boolean variable is probably not a bad method to accomplish this. You can read this article which goes into some details to clarify what exactly happens when you try to interrupt a thread and how to do it more or less reliably.