1. Sharing Chapter: Chapter 8: Thread Pool Usage
  2. Why use thread pools?
  • Reduce resource consumption. Reduce the cost of thread creation and destruction by reusing created threads.
  • Improve response speed. When a task arrives, it can be executed immediately without waiting for the thread to be created.
  • Improve thread manageability. Threads are scarce resources. If they are created without limit, they will consume system resources and reduce system stability. Thread pools can be used for uniform allocation, tuning, and monitoring
  1. Use the thread pool specification.
  • Do not use the Executors tool to create a thread pool.
  • Custom creation using TestThreadPoolExecutor is recommended.
  1. ThreadPoolExecutor Description of the thread pool class parameters.
parameter instructions
corePoolSize Number of core threads, the minimum number of threads maintained by the thread pool
maximumPoolSize A thread pool maintains the maximum number of threads
keepAliveTime The maximum idle time of any thread in the thread pool other than the core thread, after which the idle thread is destroyed
unit The unit of keepAliveTime, several static properties in TimeUnit: NANOSECONDS, MICROSECONDS, MILLISECONDS, and SECONDS
workQueue The task buffer queue used by the thread pool
threadFactory Thread factory, used to create threads, usually using the default
handler The processing policy of the thread pool for rejected tasks
5. Create a thread pool. Specify a meaningful thread name.
- Specify meaningful thread names to facilitate backtracking in case of errors. - There are three ways to specify a thread pool name, as shown belowCopy the code