gpt4 book ai didi

multithreading - 如何停止/终止/恢复受管执行人服务

转载 作者:行者123 更新时间:2023-12-03 13:19:31 25 4
gpt4 key购买 nike

我正在使用Managed Executor Service来实现处理后台任务的服务。应该允许该服务停止正在运行的任务并终止工作线程,并将其返回到线程池以进行下一个任务。一旦停止,您可以从上次停止的地方继续吗?

最佳答案

不可以,无法在Java EE环境中关闭,终止或恢复ManagedExecutorService。

根据Java EE Concurrency Utilities 1.0规范,项目符号#2

3.1.6.1 Java EE Product Provider Requirements
This subsection describes additional requirements for ManagedExecutorService providers.

  1. All tasks, when executed from the ManagedExecutorService, will run with the Java EE component identity of the component that submitted the task.
  2. The lifecycle of a ManagedExecutorService is managed by an application server. All lifecycle operations on the ManagedExecutorService interface will throw a java.lang.IllegalStateException exception. This includes the following methods that are defined in the java.util.concurrent.ExecutorService interface: awaitTermination(), isShutdown(), isTerminated(), shutdown(), and shutdownNow().
  3. No task submitted to an executor can run if task’s component is not started.

When a ManagedExecutorService instance is being shutdown by the Java EE Product Provider:

  1. All attempts to submit new tasks are rejected.
  2. All submitted tasks are cancelled if not running.
  3. All running task threads are interrupted.
  4. All registered ManagedTaskListeners are invoked.


这似乎是一个限制,但之所以有此限制,是因为ManagedExeuctorService由Java EE产品提供者为您管理。
因此,不必担心在Java EE中启动,停止或恢复ManagedExeuctorService。

现在,如果您要等到所有任务完成后,这是一个非常合理的要求。这可以通过多种方式实现:
  • 如果您一次提交所有任务,请使用 ExecutorService.invokeAll(java.util.Collection) 并跟踪返回的List>。
  • 如果您一次提交一个任务,请使用 ExecutorService.submit(Callable) ExecutorService.submit(Runnable)

  • 提交任务后,您将需要以您选择的任何方式管理 Future<T>的集合,并使用 get()(阻止)或 isDone()(非阻止)检查它们是否完成。

    关于multithreading - 如何停止/终止/恢复受管执行人服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34422485/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com