Internal Working of newFixedThreadPool

后端 未结 2 901
悲哀的现实
悲哀的现实 2021-01-20 19:43

Kindly help me in understanding the internal flow of newFixedThreadPool (or Cached)

When we write below statements, ExecutorService e=Executors.newFixedThreadPool(3)

2条回答
  •  温柔的废话
    2021-01-20 20:11

    FYI: Here is a very simple implementation of a thread pool.

    class MyThreadPool implements java.util.concurrent.Executor 
    {
        private final java.util.concurrent.BlockingQueue queue;
    
        public MyThreadPool(int numThreads) {
            queue = new java.util.concurrent.LinkedBlockingQueue<>();
            for (int i=0 ; i

    This won't compile because I didn't deal with InterruptedException, and in a real thread pool, you would also want to deal with exceptions that might be thrown by the given command, but it should give you a rough idea of what a thread pool does.

    It creates a queue and an arbitrary number of worker threads. The worker threads compete with one another to consume commands from the queue. The queue is a BlockingQueue, so the workers all sleep whenever the queue is empty.

    Other threads may produce new commands (i.e., Runnable objects), and call the execute(command) method to put the new commands in the queue. The commands will be performed (i.e., their run methods will be called) by the worker threads in approximately* the same order that they were enqueued.


    • Approximately, because worker A could pick a new command from the queue, and then lose its time slice before calling the command's .run() method. Other workers could then pick other commands from the queue and perform them before the scheduler allows worker A to run again.

提交回复
热议问题