0

0

Java并发编程:使用ExecutorService限制并发线程数

心靈之曲

心靈之曲

发布时间:2025-11-29 22:14:02

|

856人浏览过

|

来源于php中文网

原创

Java并发编程:使用ExecutorService限制并发线程数

本文详细介绍了在java中如何利用`executors`框架,特别是`executorservice`和`executors.newfixedthreadpool()`方法,来有效地限制同时运行的线程数量。通过将任务封装为`runnable`或`callable`,并提交给固定大小的线程池,开发者可以精确控制并发度,从而优化资源使用和系统性能。文章提供了完整的代码示例,并强调了线程池的正确关闭机制。

在多线程编程中,我们经常需要处理一系列独立的任务,但又希望限制同时执行的任务数量,以避免过度消耗系统资源或造成性能瓶颈。例如,当需要对一个包含大量对象的列表进行并发序列化操作时,如果为每个对象都创建一个新线程,可能会导致系统因线程过多而崩溃。Java 5引入的Executors框架为解决此类并发问题提供了强大而简洁的工具

任务定义:Runnable与Callable

在将任务提交给线程池执行之前,首先需要将任务逻辑封装起来。Java提供了两个核心接口用于定义并发任务:

  1. Runnable:

    • 定义了一个不返回任何结果,也不抛出受检查异常的任务。
    • 其核心方法是 public void run()。
    • 适用于执行不需要返回结果的异步操作。
  2. Callable<T>:

    立即学习Java免费学习笔记(深入)”;

    一点PPT
    一点PPT

    一句话生成专业PPT,AI自动排版配图

    下载
    • 定义了一个可以返回结果,并可能抛出受检查异常的任务。
    • 其核心方法是 public T call() throws Exception。
    • 适用于需要获取任务执行结果或处理特定异常的场景,通常与 Future 结合使用。

根据原始问题中对EventuelleDestination对象进行序列化的需求,我们可以将其封装为一个Runnable任务。为了使示例完整和可运行,我们创建了一些模拟类。

import com.google.gson.Gson;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Path;
import java.util.Objects;

// 模拟的业务实体和DAO层,用于使SerializationTask独立可运行
class EventuelleDestination {
    private String name;
    private EventuelAcceuillant eventuelAcceuillant;

    public EventuelleDestination(String name, EventuelAcceuillant acceuillant) {
        this.name = name;
        this.eventuelAcceuillant = acceuillant;
    }
    public EventuelAcceuillant getEventuelAcceuillant() { return eventuelAcceuillant; }
    @Override
    public String toString() { return "EventuelleDestination{" + "name='" + name + '\'' + '}'; }
}

class EventuelAcceuillant {
    private int id;
    public EventuelAcceuillant(int id) { this.id = id; }
    public int getId() { return id; }
}

class EmployeDao {
    public Employe getEmploye() { return new Employe(1001); } // 模拟获取员工
}

class Employe {
    private int id;
    public Employe(int id) { this.id = id; }
    public int getId() { return id; }
}

class EntrepriseDao {
    public int retrouveEmplacementIdParDepartementId(int deptId) { return deptId * 10; } // 模拟获取位置ID
}

/**
 * 负责将EventuelleDestination对象序列化到文件的Runnable任务。
 */
public class SerializationTask implements Runnable {
    private final EventuelleDestination eventuelleDestination;
    private final Path dossierSoumissions; // 序列化输出的基础目录
    private final EmployeDao employeDao;
    private final EntrepriseDao entrepriseDao;

    public SerializationTask(EventuelleDestination e, Path dossierSoumissions, EmployeDao employeDao, EntrepriseDao entrepriseDao) {
        this.eventuelleDestination = Objects.requireNonNull(e, "EventuelleDestination cannot be null");
        this.dossierSoumissions = Objects.requireNonNull(dossierSoumissions, "DossierSoumissions path cannot be null");
        this.employeDao = Objects.requireNonNull(employeDao, "EmployeDao cannot be null");
        this.entrepriseDao = Objects.requireNonNull(entrepriseDao, "EntrepriseDao cannot be null");
    }

    @Override
    public void run() {
        Gson gson = new Gson();
        // 根据业务逻辑构建文件名
        String filename = "/" + employeDao.getEmploye().getId() + "_" +
                          entrepriseDao.retrouveEmplacementIdParDepartementId(eventuelleDestination.getEventuelAcceuillant().getId()) + "_" +
                          eventuelleDestination.getEventuelAcceuillant().getId() + ".json";

        try (Writer writer = new FileWriter(dossierSoumissions.resolve(filename).toString())) {
            gson.toJson(eventuelleDestination, writer);
            System.out.println(Thread.currentThread().getName() + ": " + eventuelleDestination + " 已序列化到 " + filename + "...");
        } catch (IOException e) {
            System.err.println(Thread.currentThread().getName() + ": 序列化 " + eventuelleDestination + " 时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

使用ExecutorService管理线程池

ExecutorService是Executors框架的核心接口,它提供了一套用于管理和执行提交任务的机制。Executors工具类则提供了多种静态工厂方法来创建不同类型的ExecutorService实例。

为了实现固定数量的并发线程,我们使用Executors.newFixedThreadPool(int nThreads)方法。这个方法会创建一个拥有固定线程数量的线程池。当有新任务提交时,如果池中的线程数少于nThreads,则会创建一个新线程来执行任务;如果线程数已达到nThreads,则新任务会被放入等待队列,直到池中有空闲线程可用。

下面是使用newFixedThreadPool来限制并发序列化任务的示例:

import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.io.IOException;

public class FixedThreadPoolDemo {

    private final Path tempDir; // 用于存储序列化文件的临时目录
    private final EmployeDao employeDao = new EmployeDao();
    private final EntrepriseDao entrepriseDao = new EntrepriseDao();

    public FixedThreadPoolDemo() throws IOException {
        // 创建一个临时目录用于序列化输出,确保示例的整洁性
        this.tempDir = Files.createTempDirectory("serialization_output");
        System.out.println("序列化输出目录: " + tempDir.toAbsolutePath());
    }

    public void runDemo() {
        List<EventuelleDestination> destinations = new ArrayList<>();
        // 填充一些模拟数据,共10个任务
        for (int i = 1; i <= 10; i++) {
            destinations.add(new EventuelleDestination("Destination_" + i, new EventuelAcceuillant(i)));
        }

        // 定义固定线程池的大小,这里设置为3,与问题要求一致
        final int THREAD_POOL_SIZE = 3;
        ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
        System.out.println("开始使用固定大小为 " + THREAD_POOL_SIZE + " 的线程池进行序列化。");

        // 遍历列表,将每个序列化任务提交给线程池
        for (EventuelleDestination dest : destinations) {
            executorService.submit(new SerializationTask(dest, tempDir, employeDao, entrepriseDao));
        }

        // 优雅地关闭线程池
        shutdownAndAwaitTermination(executorService);
        System.out.println("所有序列化任务已完成或终止。输出文件位于: " + tempDir.toAbsolutePath());

        // 清理临时目录(可选)
        try {
            Files.walk(tempDir)
                 .sorted(java.util.Comparator.reverseOrder()) // 先删除文件,再删除空目录
                 .map(Path::toFile)
                 .forEach(java.io.File::delete);
            Files.delete(tempDir);
            System.out.println("已清理临时目录: " + tempDir.toAbsolutePath());
        } catch (IOException e) {
            System.err.println("清理临时目录时发生错误: " + e.getMessage());
        }
    }

    /**
     * 优雅地关闭ExecutorService的工具方法。
     * 参照JavaDoc中的最佳实践。
     */
    void shutdownAndAwaitTermination(ExecutorService pool) {
        pool.shutdown(); // 停止接收新任务
        try {
            // 等待已提交任务完成,最多等待60秒
            if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
                pool.shutdownNow(); // 强制取消当前正在执行的任务
                // 再次等待,确保任务响应中断
                if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
                    System.err.println("执行器服务未能终止。 " + Instant.now());
                }
            }
        } catch (InterruptedException ex) {
            // 如果当前线程在等待期间被中断,则重新取消所有任务
            pool.shutdownNow();
            // 保留中断状态
            Thread.currentThread().interrupt

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
string转int
string转int

在编程中,我们经常会遇到需要将字符串(str)转换为整数(int)的情况。这可能是因为我们需要对字符串进行数值计算,或者需要将用户输入的字符串转换为整数进行处理。php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

1031

2023.08.02

int占多少字节
int占多少字节

int占4个字节,意味着一个int变量可以存储范围在-2,147,483,648到2,147,483,647之间的整数值,在某些情况下也可能是2个字节或8个字节,int是一种常用的数据类型,用于表示整数,需要根据具体情况选择合适的数据类型,以确保程序的正确性和性能。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

613

2024.08.29

c++怎么把double转成int
c++怎么把double转成int

本专题整合了 c++ double相关教程,阅读专题下面的文章了解更多详细内容。

334

2025.08.29

C++中int的含义
C++中int的含义

本专题整合了C++中int相关内容,阅读专题下面的文章了解更多详细内容。

235

2025.08.29

javascriptvoid(o)怎么解决
javascriptvoid(o)怎么解决

javascriptvoid(o)的解决办法:1、检查语法错误;2、确保正确的执行环境;3、检查其他代码的冲突;4、使用事件委托;5、使用其他绑定方式;6、检查外部资源等等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

186

2023.11.23

java中void的含义
java中void的含义

本专题整合了Java中void的相关内容,阅读专题下面的文章了解更多详细内容。

134

2025.11.27

硬盘接口类型介绍
硬盘接口类型介绍

硬盘接口类型有IDE、SATA、SCSI、Fibre Channel、USB、eSATA、mSATA、PCIe等等。详细介绍:1、IDE接口是一种并行接口,主要用于连接硬盘和光驱等设备,它主要有两种类型:ATA和ATAPI,IDE接口已经逐渐被SATA接口;2、SATA接口是一种串行接口,相较于IDE接口,它具有更高的传输速度、更低的功耗和更小的体积;3、SCSI接口等等。

1948

2023.10.19

PHP接口编写教程
PHP接口编写教程

本专题整合了PHP接口编写教程,阅读专题下面的文章了解更多详细内容。

658

2025.10.17

TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

26

2026.03.13

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Kotlin 教程
Kotlin 教程

共23课时 | 4.4万人学习

C# 教程
C# 教程

共94课时 | 11.3万人学习

Java 教程
Java 教程

共578课时 | 81.7万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号