创建作业队列或任务控制器并在 Java 中动态添加任务

Create a Job Queue or Task Controller and dynamically add task to it in Java

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

您可以使用 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");
            });
        }
    }

}

我认为你应该使用 ExecutorService

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

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

you please give some example links

javadocs有例子。


我不明白你提出的这些异议:

But I can't use both of these solution. Because after starting ExecutorService I can't add new task to the service.

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

Because we know that it may throw InterruptedException ...

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

总之,你可以处理异常。

or ConcurrentModificationException.

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