本文介绍了Java线程池ExecutorService:线程执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们使用Java的Executor服务创建线程池并将线程提交到该线程池时,这些线程的执行顺序是什么?

As we create a Thread pool using Java's Executor service and submit threads to this thread pool, what is the order in which those threads get executed?

我想确保线程先提交,然后先执行.例如,在下面的代码中,我希望先执行前5个线程,然后再执行下5个线程,依此类推...

I want to ensure that threads submitted first, execute first.For example, in the code below, I want first 5 threads to get executed first, followed by the next 5 threads and so on...

// Create a thread pool of 5 threads.
ScheduledExecutorService exService = Executors.newScheduledThreadPool(5, new ModifiedThreadFactory("ReadThreadPool"));

// Create 100 threads.
MyThread[] threads = createMyThreads(100);

// Submit these 100 threads to thread pool for execution.
for(MyThread thread : threads) {
    exService.submit(thread);
}

Java的线程池是否为此目的提供了任何API,还是我们需要在最后实现一个FIFO队列来实现此目的?如果Java的线程池不提供任何此类功能,我真的很想了解不存在该功能背后的原因,因为这对我来说似乎是一个非常常见的用例.从技术上讲是不可能的(我认为这不太可能),还是只是错过了?

Does Java's Thread Pool provide any API for this purpose, or do we need to implement a FIFO queue at our end to achieve this.If Java's thread pool does not provide any such functionality, I am really interested to understand the reason behind the non-existence of this functionality as it appears like a very common use-case to me.Is it technically not possible (which I think is quite unlikely), or is it just a miss?

推荐答案

这是默认行为. ScheduledThreadExecutor(尽管未安排任何时间,但仍在使用)从ThreadPoolExecutor扩展而来.提交给ThreadPoolExecutor的任务存储在BlockingQueue中,直到有一个线程可以使用并执行它们.队列是FIFO.

That's the default behavior. ScheduledThreadExecutor (that you're using although you're not scheduling anything) extends from ThreadPoolExecutor. Tasks submitted to a ThreadPoolExecutor are stored in a BlockingQueue until one thread is available to take them and execute them. And queues are FIFO.

有关详细说明,请参见 javadoc .

This is decscribed in details in the javadoc.

这篇关于Java线程池ExecutorService:线程执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-01 01:04