我已經嘗試了許多不同的方法來立即停止使用ExecutorService開始的任務,但沒有運氣。如何立即停止使用ExecutorService啓動的任務?
Future<Void> future = executorService.submit(new Callable<Void>(
public Void call() {
... do many other things here..
if(Thread.currentThread.isInterrupted()) {
return null;
}
... do many other things here..
if(Thread.currentThread.isInterrupted()) {
return null;
}
}
));
if(flag) { // may be true and directly cancel the task
future.cancel(true);
}
有時候,我需要取消任務,它剛開始後,你可能會好奇,爲什麼我要做到這一點,那麼你可以想像一個塞納里奧,用戶不小心點擊「下載」按鈕開始「下載任務」,他立即想取消該操作,因爲這只是一次意外點擊。
的問題是,調用future.cancel後(真),任務沒有停止,Thread.currentThread.isInterrupted()仍然返回假,我也沒有辦法知道任務停止從call()方法中。
我想在設置一個像取消= true之後調用future.cancel(true)並在call()方法中不斷檢查該標誌,我認爲這是一個破解,代碼可能非常難看因爲用戶可以在同一時刻開始很多任務。
有沒有一種更優雅的方式來實現我想要的?
編輯:
這真的把我氣得火冒三丈。我已經在這個問題上花了差不多一天的時間了。我將嘗試爲我面臨的問題多解釋一點。
我按照以下步驟啓動5個任務,每個任務將啓動5個線程下載一個文件。然後我立即停止所有5個任務。對於下面的所有方法調用,我開始一個線程(ExecutorService.submit(task)),使它成爲異步的,就像你可以從方法的後綴中看到的那樣。
int t1 = startTaskAysnc(task1);
int t2 = startTaskAysnc(task2);
int t3 = startTaskAysnc(task3);
int t4 = startTaskAysnc(task4);
int t5 = startTaskAysnc(task5);
int stopTaskAysnc(t1);
int stopTaskAysnc(t2);
int stopTaskAysnc(t3);
int stopTaskAysnc(t4);
int stopTaskAysnc(t5);
在startTaskAysnc(),我只是啓動套接字連接到遠程服務器,以獲取該文件的大小(這當然是要花一些時間),成功後獲得的檔案大小,我將開始5個線程下載文件的不同部分。像下面的(代碼簡化,使其更易於遵循):
public void startTaskAsync(DownloadTask task) {
Future<Void> future = executorService.submit(new Callable<Void>(
public Void call() {
// this is a synchronous call
int fileSize = getFileSize();
System.out.println(Thread.currentThread.isInterrupted());
....
Future<Void> futures = new Future<Void>[5];
for (int i = 0; i < futures.length; ++i) {
futures[i] = executorService.submit(new Callable<Void>(){...});
}
for (int i = 0; i < futures.length; ++i) {
futures[i].get(); // wait for it to complete
}
}
));
synchronized (mTaskMap) {
mTaskMap.put(task.getId(), future);
}
}
public void stopTaskAysnc(int taskId) {
executorService.execute(new Runnable(){
Future<Void> future = mTaskMap.get(taskId);
future.cancel(true);
});
}
我注意到一個奇怪的行爲,我叫stopTaskAsync()後,所有5個任務,總會有至少一個任務得到停止(即Thread.currentThread.isInterrupted()返回true),其他4個任務保持運行。
我試着通過設置一個UncaughtExceptionHandler來嘗試你的建議,但沒有任何結果。
編輯:
的問題是在這個環節解決:Can't stop a task which is started using ExecutorService
嗨,@asdasd,我編輯了我的問題,如果您有線索,請給我一些幫助。謝謝。 – neevek 2011-12-26 08:34:19