[英]ExecutorService and accepting new task after shutdown when waiting for other task to finish
請提出一個適用於android應用程序的解決方案,用戶可以通過單擊按鈕來請求執行任務。
*這里的任務是非ui活動
我的表現如何:
java.util.concurrent.RejectedExecutionException:任務java.util.concurrent.ExecutorCompletionService$QueueingFuture@4198abe8從java.util.concurrent.ThreadPoolExecutor@41caf8f8拒絕了[關閉,池大小= 1,活動線程= 1,排隊的任務= 0,已完成的任務= 1]
public int onStartCommand(Intent intent, int flags, int startId) {
if (mIsAlreadyRunning) {
MyTask task = new MyTask(++count, intent);
mEcs.submit(task);
}
return super.onStartCommand(intent, flags, startId);
}
protected void onHandleIntent(Intent intent) {
if (mIsAlreadyRunning) {
return;
}
mIsAlreadyRunning = true;
final Collection<MyTask> tasks = mTasks;
MyTask yt1 = new MyTask(count, intent);
tasks.add(yt1);
// wait for finish
for (MyTask t : tasks) {
mEcs.submit(t);
}
int n = tasks.size();
for (int i = 0; i < n; ++i) {
NoResultType r;
try {
r = mEcs.take().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
mExec.shutdown();
try {
mExec.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
謝謝。
您沒有正確使用IntentService。 出現錯誤是因為在執行程序調用了shutdown()的同時提交了另一個任務。
IntentService文件:
所有請求都在單個工作線程上處理-它們可能花費必要的時間(並且不會阻塞應用程序的主循環),但是一次僅處理一個請求。
關於IntentService的onStartCommand():
您不應為IntentService覆蓋此方法。
您應該重組所有內容並使用常規服務,並在onStartCommand()中提交任務,並在onDestroy()中調用exec.shutdown()。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.