[英]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个任务:
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.