Analysis of important parameters of ThreadPoolExecutor constructor and creation of thread pool

Parametric analysis

ThreadPoolExecutor construction method

public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
    
    
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.acc = System.getSecurityManager() == null ?
                null :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }
  1. Parametric analysis
  • corePoolSize : The number of core threads defines the minimum number of threads that can run concurrently.
  • maximumPoolSize : When the tasks stored in the queue reach the queue capacity, the number of threads that can currently run simultaneously becomes the maximum number of threads.
  • workQueue: When a new task comes, it will first judge whether the number of currently running threads reaches the number of core threads. If so, the new task will be stored in the queue.

Other common parameters of ThreadPoolExecutor:

  • keepAliveTime: When the number of threads in the thread pool is greater than
  • When corePoolSize is set, if there is no new task submission at this time, the threads outside the core thread will not be destroyed immediately, but will wait until the waiting time exceeds keepAliveTime before being recycled and destroyed;
  • unit : The unit of time for the keepAliveTime parameter.
  • threadFactory : executor will be used when creating a new thread
  • handler : saturation strategy
    • ThreadPoolExecutor.AbortPolicy: Throws RejectedExecutionException to reject the processing of new tasks.
    • ThreadPoolExecutor.CallerRunsPolicy: Call to execute its own thread running task, that is, run (run) the rejected task directly in the thread that called the execute method. If the executor is closed, the task will be discarded. Therefore, this strategy will reduce the speed of submitting new tasks and affect the overall performance of the program. You can choose this strategy if your application can tolerate this delay and you require that any task request be executed.
    • ThreadPoolExecutor.DiscardPolicy: Do not process new tasks, just discard them.
    • ThreadPoolExecutor.DiscardOldestPolicy: This policy will discard the oldest outstanding task requests.

Create a simple thread pool Demo

MyRunnable.java

package ThreadPoolExecutorDemo;

import java.util.Date;

//创建一个简单的Runnable类,需要大约5s中来执行其任务
public class MyRunnable implements Runnable{
    
    
    private String command;
    public MyRunnable(String s){
    
    
        this.command = s;
    }

    @Override
    public void run(){
    
    
        System.out.println(Thread.currentThread().getName() + " start. Time = " + new Date());
        processCommand();
        System.out.println(Thread.currentThread().getName() + " End. Time = " + new Date());
    }
    
    private void processCommand(){
    
    
        try{
    
    
            Thread.sleep(5000);
        }catch(InterruptedException e){
    
    
            e.printStackTrace();
        }
    }

    @Override 
    public String toString(){
    
    
        return this.command;
    }
}

testThreadPoolExecutorDemo.java

corePoolSize: The number of core threads is 5.
maximumPoolSize: The maximum number of threads is 10.
keepAliveTime: The waiting time is 1L.
unit: The unit of waiting time is TimeUnit.SECONDS.
workQueue: The task queue is ArrayBlockingQueue, and the capacity is 100;
handler: The saturation policy is CallerRunsPolicy.

package ThreadPoolExecutorDemo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolExecutorDemo {
    
    
    private static final int CORE_POOL_SIZE = 5;
    private static final int MAX_POOL_SIZE = 10;
    private static final int QUEUE_CAPACITY = 100;
    private static final Long KEEP_ALIVE_TIME = 1L;
    public static void main(String[] args){
    
    
        //
        //
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
            CORE_POOL_SIZE,
            MAX_POOL_SIZE,
            KEEP_ALIVE_TIME,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(QUEUE_CAPACITY),
            new ThreadPoolExecutor.CallerRunsPolicy()
        );

        for(int i = 0; i < 10; i++){
    
    
            Runnable worker = new MyRunnable("" + i);
            executor.execute(worker);
        }

        //
        executor.shutdown();
        while(!executor.isTerminated()){
    
    
        }
        System.out.println("Finished all threads");
    }
}

output

pool-1-thread-1 start. Time = Thu Aug 18 10:20:30 CST 2022
pool-1-thread-3 start. Time = Thu Aug 18 10:20:30 CST 2022
pool-1-thread-4 start. Time = Thu Aug 18 10:20:30 CST 2022
pool-1-thread-2 start. Time = Thu Aug 18 10:20:30 CST 2022
pool-1-thread-5 start. Time = Thu Aug 18 10:20:30 CST 2022
pool-1-thread-1 End. Time = Thu Aug 18 10:20:35 CST 2022
pool-1-thread-3 End. Time = Thu Aug 18 10:20:35 CST 2022
pool-1-thread-4 End. Time = Thu Aug 18 10:20:35 CST 2022
pool-1-thread-5 End. Time = Thu Aug 18 10:20:35 CST 2022
pool-1-thread-2 End. Time = Thu Aug 18 10:20:35 CST 2022
pool-1-thread-5 start. Time = Thu Aug 18 10:20:35 CST 2022
pool-1-thread-4 start. Time = Thu Aug 18 10:20:35 CST 2022
pool-1-thread-3 start. Time = Thu Aug 18 10:20:35 CST 2022
pool-1-thread-1 start. Time = Thu Aug 18 10:20:35 CST 2022
pool-1-thread-2 start. Time = Thu Aug 18 10:20:35 CST 2022
pool-1-thread-3 End. Time = Thu Aug 18 10:20:40 CST 2022
pool-1-thread-1 End. Time = Thu Aug 18 10:20:40 CST 2022
pool-1-thread-5 End. Time = Thu Aug 18 10:20:40 CST 2022
pool-1-thread-4 End. Time = Thu Aug 18 10:20:40 CST 2022
pool-1-thread-2 End. Time = Thu Aug 18 10:20:40 CST 2022
Finished all threads

Flowchart + Explanation

insert image description here
In the code, 10 tasks are simulated, the number of configured core threads is 5, and the waiting queue capacity is 100, so only 5 tasks can be executed at the same time at a time, and the remaining 5 tasks will be placed in the waiting queue. If any of the current five tasks have been executed, the existing task will be executed with a new one.

Guess you like

Origin blog.csdn.net/qq_41704415/article/details/126400621