50-java 线程池的核心主件和核心类

在Java中,ThreadPoolExecutor是线程池的核心类,它在java.util.concurrent包中。Executors是一个工厂类,它提供了一些方便的方法来创建不同类型的线程池。

以下是创建线程池的核心类和方法:

  1. ThreadPoolExecutor

    构造方法:

    复制代码
    public ThreadPoolExecutor(int corePoolSize,
                             int maximumPoolSize,
                             long keepAliveTime,
                             TimeUnit unit,
                             BlockingQueue<Runnable> workQueue,
                             ThreadFactory threadFactory,
                             RejectedExecutionHandler handler)
  2. 参数说明

    • corePoolSize:线程池中的常驻核心线程数。

    • maximumPoolSize:线程池中允许的最大线程数。

    • keepAliveTime:非核心线程的空闲时间,超时自动终止。

    • unitkeepAliveTime的时间单位

    • workQueue:任务队列,被提交但未被执行的任务。

    • threadFactory:线程工厂,用于创建线程。

    • handler:拒绝策略,当任务太多无法处理时的策略。

Executors:静态方法:

复制代码
public static ExecutorService newFixedThreadPool(int nThreads)
public static ExecutorService newCachedThreadPool()
public static ExecutorService newSingleThreadExecutor()
// 等等
    • 方法说明:

      • newFixedThreadPool(int nThreads):创建固定大小的线程池。

      • newCachedThreadPool():创建一个可缓存的线程池,调用时创建线程,不使用时回收线程。

      • newSingleThreadExecutor():创建单线程化的线程池,按序执行任务。

以下是一个使用ThreadPoolExecutor的简单示例:

复制代码
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.Executor;
 
public class ThreadPoolExample {
    public static void main(String[] args) {
        BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 8, 10, TimeUnit.SECONDS, queue);
 
        for (int i = 0; i < 10; i++) {
            executor.execute(new RunnableTask());
        }
 
        executor.shutdown(); // 关闭线程池,不再接受新任务,已经提交的任务继续执行完毕
    }
 
    static class RunnableTask implements Runnable {
        public void run() {
            // 执行任务的代码
            System.out.println("Task executed on thread: " + Thread.currentThread().getName());
        }
    }
}

以上代码创建了一个ThreadPoolExecutor,并提交了10个简单的任务。线程池的核心线程数为4,最大线程数为8,超过核心线程数的非核心线程空闲时间为10秒。任务执行完毕后,关闭线程池。

相关推荐
人大博士的交易之路3 分钟前
数据结构算法——python数据结构
开发语言·数据结构·python
Han_han9196 分钟前
面向对象高级 继承(extends):
开发语言·python
前端老石人13 分钟前
邂逅前端开发:从基础到实践的全景指南
开发语言·前端·html
成都渲染101云渲染666641 分钟前
跳出“硬件堆砌”陷阱|渲染101如何用技术重构云渲染的专业价值?
java·前端·javascript
白毛大侠41 分钟前
Go Goroutine 与用户态是进程级
开发语言·后端·golang
golang学习记42 分钟前
IDEA 2026.1全新调试新特性:Spring Boot调试不再靠猜!
java·spring boot·intellij-idea
ForteScarlet1 小时前
从 Kotlin 编译器 API 的变化开始: 2.3.20
android·开发语言·后端·ios·开源·kotlin
elseif1231 小时前
浅谈 C++ 学习
开发语言·c++·学习
橘子编程1 小时前
OpenClaw(小龙虾)完整知识汇总
java·前端·spring boot·spring·spring cloud·html5
大阿明1 小时前
SpringBoot - Cookie & Session 用户登录及登录状态保持功能实现
java·spring boot·后端