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

相关推荐
num_killer4 小时前
小白的Langchain学习
java·python·学习·langchain
你怎么知道我是队长4 小时前
C语言---头文件
c语言·开发语言
期待のcode4 小时前
Java虚拟机的运行模式
java·开发语言·jvm
程序员老徐4 小时前
Tomcat源码分析三(Tomcat请求源码分析)
java·tomcat
hqwest5 小时前
码上通QT实战25--报警页面01-报警布局设计
开发语言·qt·qwidget·ui设计·qt布局控件
a程序小傲5 小时前
京东Java面试被问:动态规划的状态压缩和优化技巧
java·开发语言·mysql·算法·adb·postgresql·深度优先
仙俊红5 小时前
spring的IoC(控制反转)面试题
java·后端·spring
阿湯哥5 小时前
AgentScope Java 集成 Spring AI Alibaba Workflow 完整指南
java·人工智能·spring
HellowAmy5 小时前
我的C++规范 - 玩一个小游戏
开发语言·c++·代码规范
小楼v5 小时前
说说常见的限流算法及如何使用Redisson实现多机限流
java·后端·redisson·限流算法