Java thread pool principle

Briefly introduce the java Executors framework to manage the principle of thread pool:
//Create a thread pool with a thread size of 3
Executors.newFixedThreadPool(3);


1. How are the threads in the thread pool created? Where are they stored after creation?
public class ThreadPoolExecutor extends AbstractExecutorService {
    //Use the queue to store the tasks that need to be executed
    private final BlockingQueue<Runnable> workQueue;
    //Save Worker in HashSet, what is Worker?
    private final HashSet<Worker> workers = new HashSet<Worker>();

//Worker wraps Runnable
 private final class Worker
        extends AbstractQueuedSynchronizer
        implements Runnable
    {
       
        private static final long serialVersionUID = 6138294804551838833L;

       
        Worker(Runnable firstTask) {
            setState(-1); // inhibit interrupts until runWorker
            this.firstTask = firstTask;
            this.thread = getThreadFactory().newThread(this);
        }

      
        public void run() {
            runWorker(this);
        }
 //Look at the execute method
  public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
       
       
        int c = ctl.get();
        if (workerCountOf(c) < corePoolSize) {
           //The point is, addWorker. Well, this is where the thread is saved.
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        else if (!addWorker(command, false))
            reject(command);
    }
  
//addWorker source code
private boolean addWorker(Runnable firstTask, boolean core) {
        retry:
        for (;;) {
            int c = ctl.get();
            int rs = runStateOf(c);

            // Check if queue empty only if necessary.
            if (rs >= SHUTDOWN &&
                ! (rs == SHUTDOWN &&
                   firstTask == null &&
                   ! workQueue.isEmpty()))
                return false;

            for (;;) {
                int wc = workerCountOf(c);
                if (wc >= CAPACITY ||
                    wc >= (core ? corePoolSize : maximumPoolSize))
                    return false;
                if (compareAndIncrementWorkerCount(c))
                    break retry;
                c = ctl.get();  // Re-read ctl
                if (runStateOf(c) != rs)
                    continue retry;
                // else CAS failed due to workerCount change; retry inner loop
            }
        }

        boolean workerStarted = false;
        boolean workerAdded = false;
        Worker w = null;
        try {
            final ReentrantLock mainLock = this.mainLock;
            w = new Worker(firstTask);
            final Thread t = w.thread;
            if (t != null) {
                mainLock.lock ();
                try {
                  
                    int c = ctl.get();
                    int rs = runStateOf(c);

                    if (rs < SHUTDOWN ||
                        (rs == SHUTDOWN && firstTask == null)) {
                        if (t.isAlive()) // precheck that t is startable
                            throw new IllegalThreadStateException();
                        // save the thread
                        workers.add(w);
                        int s = workers.size();
                        if (s > largestPoolSize)
                            largestPoolSize = s;
                        workerAdded = true;
                    }
                } finally {
                    mainLock.unlock ();
                }
                if (workerAdded) {
                   // run the thread
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
        return workerStarted;
    }  

Each thread in the thread pool is encapsulated in a worker and then stored in a HashMap<Workder>.

2. How to execute when there are more tasks than threads? For example there are 5 tasks but only 3 threads are created.
See that the run method in Worker calls the runWorker method:
final void runWorker(Worker w) {
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;
        w.firstTask = null;
        w.unlock(); // allow interrupts
        boolean completedAbruptly = true;
        try {
            //The loop gets Runnable, the getTask() method gets the task from the workQueue
            while (task != null || (task = getTask()) != null) {
                w.lock();
               
                if ((runStateAtLeast(ctl.get(), STOP) ||
                     (Thread.interrupted() &&
                      runStateAtLeast(ctl.get(), STOP))) &&
                    !wt.isInterrupted())
                    wt.interrupt();
                try {
                    beforeExecute(wt, task);
                    Throwable thrown = null;
                    try {
                        task.run();
                    } catch (RuntimeException x) {
                        thrown = x; throw x;
                    } catch (Error x) {
                        thrown = x; throw x;
                    } catch (Throwable x) {
                        thrown = x; throw new Error(x);
                    } finally {
                        afterExecute(task, thrown);
                    }
                } finally {
                    task = null;
                    w.completedTasks++;
                    w.unlock();
                }
            }
            completedAbruptly = false;
        } finally {
            processWorkerExit(w, completedAbruptly);
        }
    }

Obviously this is the embodiment of the producer-consumer model. The runWorker loop blocks waiting for tasks to be taken from the workQueue. Then execute.

Summarize the principle of thread pool:
The thread pool creates threads when executing threads. Then the executed thread is not destroyed immediately but blocks waiting for a new task in the workQueue and then executes it. The thread pool is also the embodiment of the producer-consumer model.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326610638&siteId=291194637