具有共享队列的执行者

时间:2019-04-29 10:37:38

标签: java concurrency

我有一个任务生产者和多个硬件资源来执行它们 因此,我尝试使用共享队列创建执行器

BlockingQueue<Runnable> queue;
ExecutorService executor1 = new ThreadPoolExecutor(poolSize1, poolSize1, 0L, TimeUnit.MILLISECONDS, queue, threadFactory);
ExecutorService executor2 = new ThreadPoolExecutor(poolSize2, poolSize2, 0L, TimeUnit.MILLISECONDS, queue, threadFactory);
ExecutorService executor3 = new ThreadPoolExecutor(poolSize3, poolSize3, 0L, TimeUnit.MILLISECONDS, queue, threadFactory);

并且(只是尝试)将任务添加到 queue.put(task),而不是特定的 executorN.execute(task) 但是,执行程序直到 execute(task)调用才创建线程。

那么,我需要执行器执行器?在子执行程序的任何空闲线程上运行任务。 也许您知道可以使用的解决方案/库?

这不是平衡器。我不在乎任务将从何处开始。让它排队,直到被免费的处理程序拿走

1 个答案:

答案 0 :(得分:2)

我希望您手动实现它:

    BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(500);

    IntStream.range(0, 10).forEach(i -> {
      Thread t = new Thread(() -> {
        while (true) {
          try {
            queue.take().run();
          } catch (InterruptedException e) {
            break;
          }
        }
      });
      t.setDaemon(true);
      t.setName("worker-"+i);
      t.start();
    });

    queue.add(() -> System.out.println(Thread.currentThread().getName()));
    queue.add(() -> System.out.println(Thread.currentThread().getName()));
    queue.add(() -> System.out.println(Thread.currentThread().getName()));
    queue.add(() -> System.out.println(Thread.currentThread().getName()));
    queue.add(() -> System.out.println(Thread.currentThread().getName()));

    Thread.sleep(1000);

    queue.add(() -> System.out.println(Thread.currentThread().getName()));
    queue.add(() -> System.out.println(Thread.currentThread().getName()));
    queue.add(() -> System.out.println(Thread.currentThread().getName()));
    queue.add(() -> System.out.println(Thread.currentThread().getName()));
    queue.add(() -> System.out.println(Thread.currentThread().getName()));
    queue.add(() -> System.out.println(Thread.currentThread().getName()));
    queue.add(() -> System.out.println(Thread.currentThread().getName()));
    queue.add(() -> System.out.println(Thread.currentThread().getName()));

    Thread.sleep(1000);

输出将是:

worker-0
worker-1
worker-2
worker-3
worker-4
worker-5
worker-6
worker-7
worker-8
worker-9
worker-0
worker-1
worker-2

P.S。线程将等待队列中的新项目。