线程池

线程池简单使用

先看一段代码

package ThreadTest;

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

public class PoolDemo {
    public static void main(String[] args) {
        //单一线程的线程池
        //ExecutorService executorService = Executors.newSingleThreadExecutor();
        //固定个数线程的线程池
        //ExecutorService executorService = Executors.newFixedThreadPool(5);
        //可变长度的线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        try {
            for (int i = 1; i <= 100; i++) {
                int finalI = i;
                executorService.execute(()->{
                    System.out.println(Thread.currentThread().getName() + " " + finalI);
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
    }
}

线程池的七个参数

将上面线程池的源码找出来:

newSIngleThreadExecutor

image

newFixedThreadPool

image

newCachedThreadPool

image
三个线程池的核心都是下面这个函数
image
参数分析:

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.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
}
posted @   蘑菇王国大聪明  阅读(16)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示