10. 线程池
[编程语言教程]

池化技术

程序的运行,本质:占有系统的资源!优化资源的使用

池化技术:事先准备好一些资源,有人要用,就过来取,用完之后还给我。

线程池的好处

  1. 降低资源消耗
  2. 提高响应的速度
  3. 方便管理
  4. 线程可复用,可以控制最大并发数,管理线程

线程池:三大方法

package pers.vincent.matrix.subject.threadpool;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorDemo {

    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();// 可伸缩的线程池
        
        ExecutorService service1 = Executors.newSingleThreadExecutor();// 单一线程池
        
        ExecutorService service2 = Executors.newFixedThreadPool(5);// 指定线程池大小
        
        for (int i = 0; i < 100; i++) {
            service.execute(
                    () -> {
                        System.out.println(Thread.currentThread().getName());
                    });
        }

        service.shutdown();
    }

}

线程池:七大参数

源码分析:

// newSingleThreadExecutor
    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

// newFixedThreadPool
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }

// newCachedThreadPool
    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

ThreadPoolExecutor 用法

ThreadPoolExecutor

七大参数

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;
}

线程池:四种拒绝策略

// new ThreadPoolExecutor.AbortPolicy() 
// 抛出异常,拒绝新的任务

// new ThreadPoolExecutor.CallerRunsPolicy()
// 哪里来的会哪去

// new ThreadPoolExecutor.DiscardPolicy()
// 队列满了,丢掉任务,不会抛出异常

// new ThreadPoolExecutor.DiscardOldestPolicy()
// 队列满了,尝试和最早的任务竞争,也不会抛弃异常

ThreadPoolExecutor 代码示例

package pers.vincent.matrix.subject.threadpool;

import java.sql.Time;
import java.util.concurrent.*;

public class ThreadPoolExecutorDemo {

    public static void main(String[] args) {
        /**
         * 七大参数
         */
        ExecutorService executorService = new ThreadPoolExecutor(
                2,
                5,
                2,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());

        for (int i = 0; i < 5; i++) {
            // 最大任务数:maximumPoolSize + capacity
            executorService.execute(()->{
                System.out.println(Thread.currentThread().getName());
            });
        }

        executorService.shutdown();
    }

}

线程池最大的大小应该如何设置(调优)

  1. CPU 密集型: 按CPU核数设置,最大
  2. IO 密集型: 判断程序中十分耗IO的线程,核心线程数 需大于这个数

10. 线程池

原文地址:https://www.cnblogs.com/blackBlog/p/13451496.html

hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » 10. 线程池