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秒。任务执行完毕后,关闭线程池。

相关推荐
日月云棠8 小时前
各版本JDK对比:JDK 25 特性详解
java
用户8307196840829 小时前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
JavaGuide10 小时前
Claude Opus 4.6 真的用不起了!我换成了国产 M2.5,实测真香!!
java·spring·ai·claude code
IT探险家10 小时前
Java 基本数据类型:8 种原始类型 + 数组 + 6 个新手必踩的坑
java
花花无缺10 小时前
搞懂new 关键字(构造函数)和 .builder() 模式(建造者模式)创建对象
java
用户9083246027310 小时前
Spring Boot + MyBatis-Plus 多租户实战:从数据隔离到权限控制的完整方案
java·后端
桦说编程11 小时前
实战分析 ConcurrentHashMap.computeIfAbsent 的锁冲突问题
java·后端·性能优化
程序员清风15 小时前
用了三年AI,我总结出高效使用AI的3个习惯!
java·后端·面试
beata16 小时前
Java基础-13: Java反射机制详解:原理、使用与实战示例
java·后端
用户03321266636716 小时前
Java 使用 Spire.Presentation 在 PowerPoint 中添加或删除表格行与列
java