简体   繁体   English

Java - 用于固定数量任务的ExecutorService

[英]Java - ExecutorService for fixed number of tasks

I would like to achieve the following behaviour using ExecutorService from Java. 我想使用Java中的ExecutorService来实现以下行为。 I have a large number of tasks to complete which can all be done in parallel. 我有大量的任务要完成,这些任务都可以并行完成。 I would like to schedule from my main thread only N tasks at the time in the following manner: 我想以下列方式从我的主线程安排当时只有N个任务:

  • if the number of active tasks is < N => schedule new task (executor service does that already) 如果活动任务的数量是<N =>安排新任务(执行者服务已经这样做)
  • else, block on the main thread until one of the tasks is done => pretty much the same as storing N first tasks in the queue and then dequeing the first and calling get() on it) 否则,阻塞主线程,直到其中一个任务完成=>几乎与在队列中存储N个第一个任务然后对第一个任务进行dequeing并在其上调用get()相同)

Is there a way to tweak the ExecutorService to do as stated above? 有没有办法调整ExecutorService如上所述?

Use a ThreadPoolExecutor of N threads, constructed with a SynchronousQueue. 使用由SynchronousQueue构造的N个线程的ThreadPoolExecutor。 Each time you'll submit a task to the thread pool, the main thread will be blocked by the synchronous queue until a thread from the pool takes the task from the queue. 每次将任务提交到线程池时,主线程将被同步队列阻塞,直到来自池的线程从队列中获取任务。

You could submit N tasks to an ExecutorCompletionService, then in a loop: 您可以将N个任务提交给ExecutorCompletionService,然后循环:

Future<?> f = executor.take(); //blocks until one task completes
executor.submit(nextTask());

By doing that, you make sure that no more that N tasks are queued in the executor at the same time. 通过这样做,您可以确保不再有N个任务同时在执行程序中排队。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM