Thread Pool Description

1. What is a thread pool

The thread pool is actually a form of multi-thread processing. During the processing, tasks can be added to the queue, and then these tasks can be automatically started after the thread is created. The thread here is the thread we learned earlier, and the task here is the instance object that implements the Runnable or Callable interface that we learned earlier.

The advantages of the thread pool: reduce resource consumption, improve response speed, and facilitate management; threads can be reused, the maximum number of concurrency can be controlled, and threads can be managed

Second, the way to create a thread pool

  • 1 Executors.newSingleThreadExecutor();
  • Create a single thread pool
  • 2 Executors.newFixedThreadPool(int nThreads);
  • Create a thread pool with a fixed size, and fill in the thread pool size as a parameter
  • 3 Executors.newCachedThreadPool();
  • Create a scalable thread pool, if it is strong, it will be strong, and if it is weak, it will be weak

Three, the seven parameters of the thread pool

parameter describe
int corePoolSize Core thread pool size
int maximumPoolSize The most core thread pool size
long keepAliveTime overtime time
TimeUnit unit timeout unit
BlockingQueue workQueue blocking queue
ThreadFactory threadFactory Thread factory, which creates threads, generally does not need to be moved
RejectedExecutionHandler handler rejection policy

4. Four rejection strategies

rejection policy describe
new ThreadPoolExecutor.AbortPolicy() The default rejection policy of the thread pool, if the element fails to be added to the thread pool, a RejectedExecutionException will be thrown
new ThreadPoolExecutor.CallerRunsPolicy() If the addition fails, the main thread will call the execute method in the executor to execute the task
new ThreadPoolExecutor.DiscardPolicy() If the addition fails, give up without throwing an exception
new ThreadPoolExecutor.DiscardOldestPolicy() If adding to the thread pool fails, the earliest added element in the queue will be removed, and then try to add, if it fails, it will continue to retry according to this strategy

Guess you like

Origin blog.csdn.net/xmbcc777/article/details/130945044