22, JUC: 7 parameters and custom thread pool

Watch the video of the learning process: [Crazy God Says Java]
https://www.bilibili.com/video/BV1B7411L7tE?p=13
Welcome everyone to support Oh, very conscientious teacher!

Three ways to create thread pool source code

In fact, the thread pool is created by creating ThreadPoolExecutor

public static ExecutorService newSingleThreadExecutor() {
    
    
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    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,  //21亿,导致OOM
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

Create ThreadPoolExecutor source code

public ThreadPoolExecutor(int corePoolSize,  // 核心线程池大小
                              int maximumPoolSize,   // 最大核心线程池大小
                              long keepAliveTime,  // 超时了没有人调用就会释放
                              TimeUnit unit,   // 超时单位
                              BlockingQueue<Runnable> workQueue,  // 阻塞队列
                              ThreadFactory threadFactory,   // 线程工厂:创建线程的,一般不用动
                              RejectedExecutionHandler handler) {
    
      // 拒绝策略)
        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;
    }

Insert picture description here
Insert picture description here

Manually create a thread pool

java code

package com.add;

import java.util.concurrent.*;

/**
 * Created by zjl
 * 2020/11/25
 **/
/*** new ThreadPoolExecutor.AbortPolicy() // 银行满了,还有人进来,不处理这个人的,抛出异 常
 * * new ThreadPoolExecutor.CallerRunsPolicy() // 哪来的去哪里!
 * * new ThreadPoolExecutor.DiscardPolicy() //队列满了,丢掉任务,不会抛出异常!
 * * new ThreadPoolExecutor.DiscardOldestPolicy() //队列满了,尝试去和最早的竞争,也不会 抛出异常!
 * */
public class ExecutorsTest2 {
    
    
    public static void main(String[] args) {
    
    
        //自定义线程池
        ExecutorService threadPool = new ThreadPoolExecutor(
                2,   //核心线程数
                7,   //核心最大线程数
                1,   //超时时间  1s,超过1秒没人使用,会断开线程
                TimeUnit.SECONDS,  //超时单位  s
                new LinkedBlockingDeque<>(3),  //阻塞队列  大小设置3
                Executors.defaultThreadFactory(),   // 线程工厂:创建线程的,一般不用动
                new ThreadPoolExecutor.AbortPolicy()  //拒绝策略
                );
        try {
    
    
        
            for (int i = 1; i <= 2; i++) {
    
    
                threadPool.execute(()->{
    
    
                    System.out.println(Thread.currentThread().getName());
                });
            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            threadPool.shutdown();
        }
    }
}

When the number of for loops is set to 2:

At this time, the number of core threads is sufficient.
Insert picture description here
When the number of for loops is set to 4:
At this time, the number of core threads is not enough, but there are only 2 more threads, and the size of the blocking queue is 3, which is enough to store the 2 more threads, so there are still only two threads Running.
Insert picture description here
When the number of for loops is set to 6:
At this time, the number of core threads is not enough, there are 4 more threads, and the size of the blocking queue is 3, which is not enough to store the 4 extra threads, so more than two threads are running .
Insert picture description here
When the number of for loops is set to 19: the
maximum carrying capacity is the maximum number of threads + the number of blocking queues = 7+3 =10.
At this time, the maximum carrying capacity has been exceeded, and this rejection strategy will report a rejection exception.

pool-1-thread-1
pool-1-thread-3
pool-1-thread-2
pool-1-thread-3
pool-1-thread-4
pool-1-thread-2
pool-1-thread-1
pool-1-thread-2
pool-1-thread-5
pool-1-thread-4
pool-1-thread-4
pool-1-thread-3
pool-1-thread-4
pool-1-thread-7
pool-1-thread-5
pool-1-thread-2
pool-1-thread-6
pool-1-thread-1
java.util.concurrent.RejectedExecutionException: Task com.add.ExecutorsTest2$$Lambda$1/668386784@10f87f48 rejected from java.util.concurrent.ThreadPoolExecutor@b4c966a[Running, pool size = 7, active threads = 3, queued tasks = 0, completed tasks = 15]
	at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
	at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
	at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
	at com.add.ExecutorsTest2.main(ExecutorsTest2.java:30)

Process finished with exit code 0

Guess you like

Origin blog.csdn.net/qq_41347385/article/details/110127878