我寫過類VideoProcessor,它對視頻進行了一些重處理。如果「啓動」,則會創建一個新線程,並將該參考保存在 videoProcessingThread的字段中。現在的問題是:調用線程上的中斷(),但它永遠不會中斷
videoProcessingThread.interrupt();
這似乎沒有任何作用,因爲isInterrupted()永遠不會計算爲true。我也加了其他中斷檢查,只是爲了確定;但他們也不「工作」。我已經實施了一種解決方法:
videoProcessingThread.kill();
這似乎實際上是「殺死」線程。方法kill將布爾變量 kill設置爲true,並且正確計算並且線程返回。
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;
}
}
我在做什麼錯?
您評論http://stackoverflow.com/questions/8627719/interrupt-doesnt-work? – ziesemer
是重處理(或稱爲那裏的任何方法)捕獲InterruptedException或檢查中斷標誌? –
如何調用由匿名類聲明的方法?換句話說,'videoProcessingThread'是Thread,它沒有kill方法。你怎麼稱呼它?切線位,但只是好奇。 – erickson