Java Thread Pool ExecutorService: Threads execution order

旧城冷巷雨未停 提交于 2019-12-08 15:02:27

问题


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?

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);
}

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?


回答1:


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.

This is decscribed in details in the javadoc.




回答2:


Threads do not get executed. Threads are the entities running taska like Runnable and Callable . Submiting such a task to a executor service will put it in it's inner BlockingQueue until it gets picked up by a thread from it's thread pool. This will still tell you nothing about the order of execution as different classes can do different things while implementing Runnable



来源:https://stackoverflow.com/questions/24477316/java-thread-pool-executorservice-threads-execution-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!