You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何限制Java序列化任务的同时运行线程数至3个?

限制并发数为3的序列化任务实现

要实现同时最多3个线程执行序列化操作,直接用Java标准库的ExecutorService创建固定大小的线程池即可,这是简洁可靠的实现方式,无需手动管理线程生命周期。

具体实现步骤

  • 创建固定大小为3的线程池,限制并发执行的线程数量
  • 遍历目标列表,将每个序列化任务提交到线程池
  • 任务全部提交后,关闭线程池并等待所有任务执行完成

完整代码示例

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class SerializationService {
    // 业务依赖对象(根据实际场景注入)
    private EmployeDao employeDao;
    private EntrepriseDao entrepriseDao;
    private File dossierSoumissions;

    // 序列化方法:优化资源释放逻辑,避免泄漏
    public void serializeDestinationEmploye(EventuelleDestination e) {
        Gson gson = new Gson();
        String filename = "/" + employeDao.getEmploye().getId() + "_" 
                        + entrepriseDao.retrouveEmplacementIdParDepartementId(e.getEventuelAcceuillant().getId()) 
                        + "_" + e.getEventuelAcceuillant().getId() + ".json";

        // 用try-with-resources自动关闭Writer,无需手动调用close()
        try (Writer writer = new FileWriter(dossierSoumissions.toString() + filename)) {
            gson.toJson(e, writer);
            System.out.println(e + " has been serialized...");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    // 批量处理序列化任务的核心方法
    public void processAllDestinations(List<EventuelleDestination> ev) {
        // 创建固定大小为3的线程池,严格限制并发数
        ExecutorService executor = Executors.newFixedThreadPool(3);

        // 遍历列表提交任务
        for (EventuelleDestination e : ev) {
            executor.submit(() -> serializeDestinationEmploye(e));
        }

        // 关闭线程池:不再接受新任务,等待已提交任务执行完毕
        executor.shutdown();
        try {
            // 等待所有任务完成,可根据实际需求调整超时时间
            if (!executor.awaitTermination(1, TimeUnit.HOURS)) {
                // 超时未完成则强制终止线程池
                executor.shutdownNow();
            }
        } catch (InterruptedException ie) {
            // 等待过程被中断,强制终止并恢复线程中断状态
            executor.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}

关键说明

  • Executors.newFixedThreadPool(3)创建的线程池,核心线程数与最大线程数均为3,待执行任务会放入无界队列等待,确保同时运行的线程数不超过3个。
  • 线程池会自动复用线程,避免频繁创建销毁线程的性能开销,比手动创建Thread对象更高效稳定。
  • 使用try-with-resources管理Writer资源,能保证异常场景下资源也会被正确关闭,避免文件句柄泄漏。
  • 必须调用shutdown()关闭线程池,否则线程池的非守护线程会阻止程序正常退出;awaitTermination()用于等待所有任务完成,防止主线程提前结束。

内容的提问来源于stack exchange,提问作者p3terson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 14:30:16