The use of four types of thread pools in Java

First, the meaning of each parameter of the thread pool function prototype


ThreadPoolExecutor mExecutor = new ThreadPoolExecutor(
corePoolSize, // 核心线程数
maximumPoolSize, // 最大线程数
keepAliveTime, // 闲置线程存活时间
TimeUnit.MILLISECONDS ,// 时间单位
new LinkedBlockingDeque<Runnable>(), // 线程队列
Executors.defaultThreadFactory(), // 线程工厂
new AbortPolicy() // 队列已满,而且当前线程数已经超过最大线程数时的异常处理策略
)

For example, go to the train station to buy tickets, there are 10 ticket windows, but only 5 windows are open to the outside world. Then the 5 windows open to the outside world are called the number of core threads , and the maximum number of threads is 10 windows . If there are 5 windows are all occupied, then the people who come later have to queue in the back, but then there are more and more people in the ticket office, and it is already full, just like the thread queue is full. At this time, the station master ordered to put the remaining 5 windows It also opened, that is to say, there are already 10 windows running at the same time. Later, a group of people came, and the 10 windows could not be processed, and the ticket hall was full. At this time, the station master ordered the entrance to be blocked and not allowed When other people come in again, this is the thread exception handling strategy . The thread survival time refers to the maximum time allowed for the conductor to rest, thus limiting the lazy behavior of the conductor.

2. Four commonly used thread pools in java

Java provides four thread pools through Executors:
newCachedThreadPool creates a cacheable thread pool. If the length of the thread pool exceeds the processing requirement, idle threads can be flexibly recovered. If there is no recovery, a new thread will be created.
newFixedThreadPool creates a fixed-length thread pool that can control the maximum number of concurrent threads. Exceeded threads will wait in the queue.
newScheduledThreadPool creates a fixed-length thread pool that supports scheduled and periodic task execution.
newSingleThreadExecutor creates a single-threaded thread pool that only uses a single worker thread to execute tasks, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority).

Guess you like

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