This article is about thread pooling in Java:
Common thread pools in 4:
1.Executors.newCachedThreadPool();Create a cacheable thread pool. If the thread length exceeds the processing requirements, you can flexibly recycle idle threads. If there are no threads to recycle, create a new thread. 2.Executors.newFixedThreadPool(5);Create a specified number of thread pools that control the maximum number of concurrent threads. 3.Executors.newScheduledThreadPool(10);Create a thread pool of fixed length to support scheduled and periodic task collection.A thread pool dedicated to timed tasks that knows how long it will take to execute; 4.Executors.newSingleThreadExecutor();Create a single threaded thread pool that only uses a single worker thread to perform tasks, ensuring all tasks5.**Executors.defaultThreadFactory(); ** Default thread pool
A 2-minute way to create a thread pool:
- The first:
public static ExecutorService service = Executors.newFixedThreadPool(10);
public static class Thread01 extends Thread{
@Override
public void run(a) {
System.out.println("Current thread"+Thread.currentThread().getId());
int i = 10/2;
System.out.println("Running thread"+i); }}public static class Runnable01 implements Runnable{
@Override
public void run(a) {
System.out.println("Current thread"+Thread.currentThread().getId());
int i = 10/2;
System.out.println("Running thread"+i); }}Copy the code
Activation:
service.execute(new Thread01());
service.execute(new Runnable01());
Copy the code
- The second,
ThreadPoolExecutor executor = new ThreadPoolExecutor(5.200.10,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(10000),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
Copy the code
The thread pool created by this method has seven parameters, and we can use it reasonably only after we know its meaning. We enter its underlying implementation, as shown in the figure:
- Int corePoolSize: Number of core threads, which are kept in the thread pool (even if the system is idle, unless allowCoreThreadTimeOut is set), that is, the number of threads ready after the pool is created, waiting to receive asynchronous tasks.
- Int maximumPoolSize: specifies the maximum number of threads to control resources.
- Long keepAliveTime: keepAliveTime, if the current number of threads > core number, free idle threads (maximumPoolSize-corePoolSize)(as Long as the thread is free > keepAliveTime).
- TimeUnit Unit: indicates the unit of survival time. BlockingQueue
- WorkQueue: Blocks a queue. If there are many tasks, the redundant tasks are put in the queue first. When there are idle threads, new threads are fetched from the queue to continue executing the tasks.
- ThreadFactory ThreadFactory: Thread creation factory. RejectedExecutionHandler
- Handler (rejection policy): If the queue is full and no more tasks can be stored, we will reject our task according to our specified rejection policy.
Rejection strategy:
The default util package has 4 rejection strategies: 1. Discard the oldest task; 2. Discard the new task directly and throw exception 3. Directly invoking the run method is equivalent to synchronous invocation. 4. Discard the new task without throwing an exception
Thread pool work order/flow:
1. The thread pool is created first, and corePoolSize number of core threads are ready to receive tasks; 2.1 If corePoolSize is full, the task is placed in the blocking queue, and when corePoolSize is free, the task is fetched from the task pair column 2.2 If the blocking queue is also full, a new thread can be opened up to maximumPoolSize. 2.3 If maximumPoolSize is also full, the number of idle maximumPoolSize threads with corePoolSize is automatically destroyed after keepAliveTime, and eventually remains at corePoolSize threads If the thread reaches maximumPoolSize and a new task comes in, reject is used to process it. 3 So thread creation is created by threadFactory.
Note: new LinkedBlockingQueue < > (); The default is the maximum value of Integer; (May result in insufficient memory, so be sure to save as a fixed number)
Benefits of using thread pools:
- Reduce resource consumption
Reduce thread creation and destruction costs by reusing already created threads. 2. Increase the response speed because the thread pool has not exceeded the maximum limit of the thread pool, some threads are waiting for the task to be assigned, when the task comes, without creating a new thread can execute; 3. Improve the manageability of threads The thread pool will optimize the processing of threads in the pool according to the characteristics of the current system, reducing the system overhead caused by the creation and destruction of threads; Infinite create and destroy threads not only consume system resources, but also reduce system stability,