Thread pool
Definitions and methods
When the thread pool works, it controls the number of running threads, puts tasks into the queue during processing, and then starts these tasks after the threads are created. If the number of threads exceeds the maximum number, the exceeded threads queue up and wait for other threads to complete execution, and then take tasks out of the queue for execution.
characteristic:
Thread reuse, control the maximum number of concurrent threads, and manage threads.
Benefits:
- Reduce resource consumption. Reduce the consumption caused by thread creation and destruction by reusing the created threads.
- Improve response speed. When the task arrives, the task can be executed immediately without waiting for the thread to be created
- Improve thread manageability. When threads are scarce resources, if they are created without restriction, it will not only consume system resources, but also reduce the stability of the system. Using thread pool can be used for unified allocation, tuning and monitoring.
Simple architecture diagram:
We actually use ThreadPoolExecutor
Alibaba development specification manual:
[mandatory] thread pools are not allowed to be created using Executors, but through ThreadPoolExecutor. This processing method makes the writing students more clear about the running rules of thread pools and avoid the risk of resource depletion.
Note: the disadvantages of the thread pool object returned by Executors are as follows:
1) FixedThreadPool and SingleThreadPool:
The allowed request queue length is integer MAX_ Value, which may accumulate a large number of requests, resulting in OOM.
2)CachedThreadPool:
The number of threads allowed to create is integer MAX_ Value, a large number of threads may be created, resulting in OOM.
The following operations need to be understood:
First, use the tool class (Executors) to create a thread pool:
FixedThreadPool is called a reusable thread pool with a fixed number of threads. It has good performance in executing long-term tasks. It creates a thread pool with N fixed threads and a thread pool with a fixed number of threads.
public class demo1 { public static void main(String[] args) { //Use the Executors tool class to create a newFixedThreadPool thread pool ExecutorService executor = Executors.newFixedThreadPool(3); try{ for (int i = 0; i < 10; i++) { executor.execute(()->{ System.out.println(Thread.currentThread().getName()+"Task execution"); }); } } finally { executor.shutdown(); } } }
Singlethreadexecution is an Executor that uses a single worker thread, eliminating the resource consumption when creating and destroying threads.
public class demo1 { public static void main(String[] args) { ExecutorService executor = Executors.newSingleThreadExecutor(); try{ for (int i = 0; i < 10; i++) { executor.execute(()->{ System.out.println(Thread.currentThread().getName()+"\t Task execution"); }); } } finally { executor.shutdown(); } } }
CachedThreadPool is a thread pool that creates new threads as needed. Scalable thread pool.
public class demo1 { public static void main(String[] args) { //Use the Executors tool class to create a newFixedThreadPool thread pool //ExecutorService executor = Executors.newFixedThreadPool(3); //One thread pool is one thread //ExecutorService executor = Executors.newSingleThreadExecutor(); ExecutorService executor = Executors.newCachedThreadPool(); try{ for (int i = 0; i < 10; i++) { executor.execute(()->{ System.out.println(Thread.currentThread().getName()+"\t Task execution"); }); } } finally { executor.shutdown(); } } }
pool-1-thread-2 Task execution pool-1-thread-1 Task execution pool-1-thread-4 Task execution pool-1-thread-3 Task execution pool-1-thread-5 Task execution pool-1-thread-6 Task execution pool-1-thread-7 Task execution pool-1-thread-8 Task execution pool-1-thread-9 Task execution pool-1-thread-10 Task execution
The process of using thread pools when setting deferred operations to mimic time-consuming code.
package com.JucPool; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * Basic understanding and three methods of thread pool */ public class demo1 { public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); try{ for (int i = 0; i < 10; i++) { //Pause for a few seconds try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } executor.execute(()->{ System.out.println(Thread.currentThread().getName()+"\t Task execution"); }); } } finally { executor.shutdown(); } } }
pool-1-thread-1 Task execution pool-1-thread-1 Task execution pool-1-thread-1 Task execution pool-1-thread-1 Task execution pool-1-thread-1 Task execution pool-1-thread-1 Task execution pool-1-thread-1 Task execution pool-1-thread-1 Task execution pool-1-thread-1 Task execution pool-1-thread-1 Task execution Process finished with exit code 0
At this point, it is reduced to the singlethreadexecution thread pool.
Simple source code analysis
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); } public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); } public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
By contrast, the bottom layer is realized through ThreadPoolExecutor, but the parameters are different, and the parameters transferred are also related to the blocking queue.
Parameters: (very important)
- ·corePool: the size of the thread pool's resident core thread pool.
- ·maximumPool: the size of the maximum thread pool -- the maximum number of threads that can be executed simultaneously in the thread pool
- keepAliveTime: the survival time of redundant idle threads. When the number of threads in the current pool exceeds the corePool and the idle time reaches keepAliveTime, the redundant threads will be destroyed until only corePool threads are left
- Unit – the time unit of the keepAliveTime parameter
- workQueue – a queue used to save tasks before they are executed. This queue will only hold Runnable tasks submitted by the execute method.
There are also two parameters in ThreadPoolExecutor:
- ThreadFactory: refers to the thread factory that generates the working threads in the thread pool. It is used to create threads. It is generally the default
- Handler: reject policy, which indicates how to reject the runnable request execution when the queue is full and the working thread exceeds the maximum thread pool size
The above is a summary of the seven parameters in the thread pool, which is very important. In terms of when to go to the reject policy, the execution process of the thread pool will be analyzed later.