【问题标题】:Create a Job Queue or Task Controller and dynamically add task to it in Java创建作业队列或任务控制器并在 Java 中动态添加任务
【发布时间】:2017-05-09 20:10:11
【问题描述】:

大家好,我想创建一个作业队列来执行多个任务。但是,我的要求是我应该能够随时将任务添加到该作业队列中,并且所有这些任务都应该按顺序执行。我在互联网上搜索了一些解决方案,发现这两个链接 1)Java Thread Pool Executor Example 2)Java Executor Framework Tutorial and Best Practices。但我不能同时使用这两种解决方案。因为启动 Executor 服务后,我无法向服务添加新任务。因为我们知道它可能会抛出 InterruptedException 或 ConcurrentModificationException。

【问题讨论】:

  • 使用BlockingQueue 来保存runnables 并在后台线程中继续删除和执行?
  • 能否提供一些示例链接

标签: java multithreading executorservice


【解决方案1】:

您可以使用BlockingQueue 在单独的线程中继续等待,直到出现一个或多个Runnable。

public class Mainer {
    private static final BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(15);

    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            while (true) {
                try {
                    queue.take().run();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });
        t.start();

        for (int i = 0; i < 10; i++) {
            queue.add(() -> {
                System.out.println("Hello");
            });
        }
    }

}

【讨论】:

  • 这是我真正需要的.. :)
  • 很高兴它有帮助。
【解决方案2】:

我认为您应该使用ExecutorService。

  • 它维护要运行的任务队列。如果需要,您可以提供自己的队列。
  • 可以随时使用submit 方法添加新任务。
  • 提交任务时可以获得Future。
  • 可以一次运行一个任务,也可以使用一组工作线程并行运行。
  • 如果您使用多个线程,则各种执行器服务实现会提供不同的池管理策略。
  • 有排空和关闭服务的操作。

如果您想要一个始终一次运行一个任务的ExecutorService,请确保指定一个最大大小为一个线程的线程池。

请提供一些示例链接

javadocs 有例子。


我不明白你提出的这些反对意见:

但我不能同时使用这两种解决方案。因为在启动ExecutorService 后我无法向服务添加新任务。

是的,你可以。这就是ExecutorService.submit(...) 所做的。

因为我们知道它可能会抛出InterruptedException ...

如果您的应用程序在当前线程等待Future 或关闭ExecutorService 时调用Thread.interrupt(),它只会抛出InterruptedException。 (如果您使用 invoke 或 invokeAll 也可能发生这种情况,但显然您的用例并不要求您立即等待任务结果。)

无论如何,你可以处理异常。

或ConcurrentModificationException。

AFAIK,ExecutorService 可以抛出 ConcurrentModificationException 的唯一情况是,如果您使用的是未正确实现的自定义 Queue 类。

【讨论】:

    猜你喜欢
    • 2011-05-19
    • 2013-09-01
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多