計劃的任務要麼正在執行或正在等待被執行。
如果任務正在等待執行,future.cancel()
將阻止它被執行(取消(true)/取消(false))。
如果任務已被執行,future.cancel(false)
將不起作用。 future.cancel(true)
將中斷執行該任務的線程。 這是否會產生任何影響取決於您誰將執行該任務。根據實施情況,任務可能會或可能不會響應中斷。
爲了使您的任務響應取消,您必須實施doSomething()
,以便它能響應中斷。
有做到這一點基本上有兩種方式:
1.檢查中斷標誌在你的邏輯
public void doSomething(){
stuff();
//Don't use Thread.interrupt()
if(Thread.currentThread().isInterrupted()){
// We have an interruption request, possibly a cancel request
//Stop doing what you are doing and terminate.
return;
}
doLongRunningStuff();
}
您必須偶爾檢查中斷標誌,如果中斷,停止你正在做什麼並返回。確保使用Thread.isInterrupted()而不是Thread.interrupt()進行檢查。在追訪例外
2.Act
public void doSomething(){
try{
stuff();
}catch(InterruptedException e){
// We have an interruption request, possibly a cancel request
// First, preserve Interrupted Status because InterruptedException clears the
// interrupted flag
Thread.currentThread.interrupt();
// Now stop doing your task and terminate
return;
}
doLongRunningStuff();
}
當你拋出InterruptedException的任何方法,一定要阻止你做什麼,當一個人被拋出終止。
一旦以這種方式實現您的方法,您可以調用future.cancel(true)來取消執行正在運行的任務。
doSomething()發生了什麼? – 2010-05-25 09:17:37