当前位置:网站首页>Seven parameters of thread pool and custom thread pool

Seven parameters of thread pool and custom thread pool

2022-06-22 06:18:00 Kuxiaoya

The first part describes three methods of thread pool , First review the following :

Executors.newSingleThreadExecutor(); Single thread

Executors.newFixedThreadPool(5); Fixed number of threads

Executors.newCachedThreadPool(); Buffer pool , Scalable

Let's see “ Three ways ” Source code analysis , In this way, we can better understand “ Seven parameters ”:

//Executors.newSingleThreadExecutor();  Single thread 
// Source code analysis :
public static ExecutorService newSingleThreadExecutor() {
    
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
}   

//Executors.newFixedThreadPool(5);  Fixed number of threads 
// Source code analysis : 
public static ExecutorService newFixedThreadPool(int nThreads) {
    
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
}   

//Executors.newCachedThreadPool();  Buffer pool , Scalable 
// Source code analysis : 
public static ExecutorService newCachedThreadPool() {
    
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,//21 Billion  OOM:Out Of Memory, out of memory 
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
}    

Source code analysis :( There are three methods ThreadPoolExecutor)

Continue clicking ThreadPoolExecutor , View source code :

// The essence : ThreadPoolExecutor

public ThreadPoolExecutor(int corePoolSize,// Core thread pool size 
                              int maximumPoolSize,// Maximum core thread pool size 
                              long keepAliveTime,// If no one calls after the timeout, it will be released 
                              TimeUnit unit, // Timeout unit 
                              BlockingQueue<Runnable> workQueue,// Blocking queues 
                              ThreadFactory threadFactory,// Thread factory :  Create thread of , Generally don't move 
                              RejectedExecutionHandler handler// Refusal strategy ) {
    
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.acc = System.getSecurityManager() == null ?
                null :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

Get seven parameters :

int corePoolSize,// Core thread pool size 
int maximumPoolSize,// Maximum core thread pool size 
long keepAliveTime,// If no one calls after the timeout, it will be released 
TimeUnit unit, // Timeout unit 
BlockingQueue<Runnable> workQueue,// Blocking queues 
ThreadFactory threadFactory,// Thread factory :  Create thread of , Generally don't move 
RejectedExecutionHandler handler// Refusal strategy 



Custom thread pool :

package pool;

import java.util.concurrent.*;

public class Demo2 {
    
    public static void main(String[] args) {
    

        //  Custom thread pool ! Work  ThreadPoolExecutor( Seven parameters )
        ExecutorService threadPool = new ThreadPoolExecutor(
          2,
          5,
          3,
          TimeUnit.SECONDS,
          new LinkedBlockingDeque<>(3),
          Executors.defaultThreadFactory(),
          // There are four rejection strategies , Use what suits you !
          new ThreadPoolExecutor.DiscardOldestPolicy() // The queue is full , Try to compete with the earliest , It doesn't throw an exception !
        );

        try {
    
            // Maximum bearing capacity : Deque + max
            // exceed  RejectedExecutionException  Throw a reject execution exception 
            for (int i = 1; i <= 9; i++) {
    
                // After using the thread pool , Use thread pool to create threads 
                threadPool.execute(()->{
    
                    System.out.println(Thread.currentThread().getName()+" OK!");
                });
            }
        } catch (Exception e) {
    
            e.printStackTrace();
        } finally {
    
            // Out of thread pool , Program end , Close thread pool 
            threadPool.shutdown();
        }
    }
}	

Four rejection strategies :

1、new ThreadPoolExecutor.AbortPolicy()

The bank is full , There are people coming in , Just don't deal with this person ,
Throw a reject execution exception RejectedExecutionException

Running results :

 Insert picture description here

2、new ThreadPoolExecutor.CallerRunsPolicy()

Where you come from, where you go !

Running results :

 Insert picture description here

3、new ThreadPoolExecutor.DiscardPolicy()

The queue is full , Lose the job , Does not throw an exception

Running results :

 Insert picture description here

4、new ThreadPoolExecutor.DiscardOldestPolicy()

The queue is full , Try to compete with the earliest , It doesn't throw an exception !

Running results :

 Insert picture description here

原网站

版权声明
本文为[Kuxiaoya]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220609550394.html