Inner work of newFixedThreadPool

Please help me in understanding the inner thread of newFixedThreadPool (or Cached)

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

  • e.execute (runaable1);
  • e.execute (runaable2);
  • e.execute (runaable3);
  • e.execute (runaable4);
  • e.execute (runaable5);

up to 3 execution methods, three threads will be created, when the 4th execution method is called, a new thread will not be created, but the work will wait until the thread becomes free.

I do not understand this point: "a new thread will not be created, but the work will wait until the thread becomes free." what I think, when runnable1 is provided to the first created thread, as soon as the runnable1 method is launched, the completion of Thread1 will also be completed, thread1 will not be able to call the run method runableable4. So how java manages to execute 5 runnable in just 3 threads.

+3
source share
2 answers

FYI: This is a very simple thread pool implementation.

class MyThreadPool implements java.util.concurrent.Executor 
{
    private final java.util.concurrent.BlockingQueue<Runnable> queue;

    public MyThreadPool(int numThreads) {
        queue = new java.util.concurrent.LinkedBlockingQueue<>();
        for (int i=0 ; i<numThreads ; i++) {
            new Thread(new Runnable(){
                @Override
                public void run() {
                    while(true) {
                        queue.take().run();
                    }
                }
            }).start();
        }
    }

    @Override
    public void execute(Runnable command) {
        queue.put(command);
    }
}

, InterruptedException, , command, , .

. , . - BlockingQueue, , .

(.. Runnable objects) execute(command) . (.. ) , .


  • , A , .run(). , A.
+3

ExecutorService e=Executors.newFixedThreadPool(3);, . 3 , e.

ExecutorService, , , , - , .

, , pipleline , - , .

:
. , , , , ( , , - - ), , . , 4 5 , .

" , ".

, , , , , , .

, newFixedThreadPool, 3 , , ExecutorService, e.

:
, java.util.concurrent.Executors. , Executors#newCachedThreadPool(), , , , .
.

+1

Source: https://habr.com/ru/post/1657885/


All Articles