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

相关推荐
皮皮林5513 小时前
Java性能调优黑科技!1行代码实现毫秒级耗时追踪,效率飙升300%!
java
冰_河3 小时前
QPS从300到3100:我靠一行代码让接口性能暴涨10倍,系统性能原地起飞!!
java·后端·性能优化
桦说编程6 小时前
从 ForkJoinPool 的 Compensate 看并发框架的线程补偿思想
java·后端·源码阅读
躺平大鹅8 小时前
Java面向对象入门(类与对象,新手秒懂)
java
初次攀爬者9 小时前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺9 小时前
搞懂@Autowired 与@Resuorce
java·spring boot·后端
Derek_Smart10 小时前
从一次 OOM 事故说起:打造生产级的 JVM 健康检查组件
java·jvm·spring boot
NE_STOP11 小时前
MyBatis-mybatis入门与增删改查
java
孟陬14 小时前
国外技术周刊 #1:Paul Graham 重新分享最受欢迎的文章《创作者的品味》、本周被划线最多 YouTube《如何在 19 分钟内学会 AI》、为何我不
java·前端·后端