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

相关推荐
Awna6 分钟前
Golang 大小写可见性规范
开发语言·后端·golang
孙启超17 分钟前
【AI应用开发】LangChain 中 Chain 和 Agent 核心区别?
java·人工智能·langchain·llm·rag·ai应用开发·agent loop
leoZ23129 分钟前
实战复盘:用 Claude Code 从零搭一个 GitHub PR 统计工具
java·人工智能·python·深度学习·自然语言处理·github·llama
William Dawson33 分钟前
【踩坑实录|Hive1\.2\.1数据服务接口5大疑难问题调试与全方位优化方案】
java·hive·spring boot
2601_955759881 小时前
如何识别 Claude API 低价值调用并优化
java
AI科技星1 小时前
曲率‑挠率与 $\boldsymbol{\omega/c}$ 的关系、精算验证及其物理意义
c语言·开发语言·线性代数·算法·决策树·机器学习·ai科技星
鹿角片ljp1 小时前
Java框架篇:Spring + SpringMVC + SpringBoot + MyBatis深度复习
java·开发语言
Lyra_Infra2 小时前
Java 应用启动脚本 JDK 路径适配优化文档
java·shell
CodeHackerBhx2 小时前
Spring Boot 4 防重复提交:从接口幂等到 Redis 分布式锁的完整实践
java·数据库·spring boot·redis·分布式
xlxxy_2 小时前
外部系统调用SAP接口遇到的一些报错
开发语言·数据库·sap·abap