ExecutorService并在等待其他任务完成后关闭后接受新任务

时间:2014-08-02 12:13:52

标签: java android multithreading executorservice

请为Android应用程序建议一个解决方案,用户可以通过单击按钮请求执行任务。

*此处任务是非ui活动

  • 我需要允许用户执行多个请求
  • 在多任务执行任务期间,激励器应该等待完成所有任务。
  • 当任务完成多个任务并且任务执行器正在等待其他任务完成时,如果用户请求其他任务 任务,所以我应该被接受并执行。
  • 此任务应该在android服务中发生,因此在退出应用程序时它不应该终止。

我的表现如何:

  • 我正在使用ExcutorService& amp; ExecutorCompletionService因为任务执行程序而抛出错误 等待其他任务完成,如果用户请求其他任务

java.util.concurrent.RejectedExecutionException:java.util.concurrent.ThreadPoolExecutor@41caf8f8中的任务java.util.concurrent.ExecutorCompletionService$QueueingFuture@4198abe8 [关闭,池大小= 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();
            }

    }

感谢。

1 个答案:

答案 0 :(得分:1)

您未正确使用IntentService。它提供错误是因为您在执行程序已经调用shutdown()时提交了另一个任务。

IntentService的文档:

  

所有请求都在一个工作线程上处理 - 它们可以作为   只要有必要(并且不会阻止应用程序的主循环),   但一次只能处理一个请求。

关于IntentService的onStartCommand():

  

您不应该为IntentService覆盖此方法。

您应重组所有内容并使用常规服务,其中任务在onStartCommand()中提交,并在onDestroy()中调用exec.shutdown()。

相关问题