【问题标题】:ExecutorService and accepting new task after shutdown when waiting for other task to finishExecutorService 并在等待其他任务完成时在关机后接受新任务
【发布时间】:2014-08-02 12:13:52
【问题描述】:

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

*这里的任务是非ui活动

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

我的表现如何:

  • 我正在使用 ExcutorService & ExecutorCompletionService 它会抛出错误,因为任务执行器是 等待其他任务完成,然后如果用户请求其他任务

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();
            }

    }

谢谢。

【问题讨论】:

    标签: java android multithreading executorservice


    【解决方案1】:

    您没有正确使用 IntentService。它给出了错误,因为您在执行程序调用了 shutdown() 时提交了另一个任务。

    IntentService 文档:

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

    关于 IntentService 的 onStartCommand():

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

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

    【讨论】:

    • 我需要允许用户同时执行多个请求(任务),所以我猜这个解决方案不会达到目的。请提出建议。
    • 常规服务将同时允许多个请求。您在 onStartCommand() 中将请求提交给执行程序。 IntentService 是错误的方式,它适用于串行请求。
    • 谢谢。这适用于多个任务,但服务没有停止。它的继续运行和销毁没有像您建议的那样被调用。它应该关闭一项任务完成。我需要在销毁时广播一些东西。请提出建议。
    • Service继续运行有什么危害?任务运行完成,它什么也不做,等待下一个任务直到被系统销毁。
    • 我确信有一种方法可以安装它来 stopself() 服务,但是为什么呢? Android 会在需要时对其进行清理。
    猜你喜欢
    • 2021-08-14
    • 2013-05-26
    • 1970-01-01
    • 2011-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多