嵌套for循环在外层循环和内层循环中使用两个Executors.newCachedThreadPool缓存线程池执行操作

1. 首先,我们需要创建两个ExecutorService对象,这两个对象将作为我们的缓存线程池。

2. 然后,我们使用嵌套的for循环来执行我们的操作。在每个外层循环中,我们将创建一个新的任务并提交给外层线程池。在这个任务中,我们将创建一个新的内层循环,并在每个内层循环中创建一个新的任务并提交给内层线程池。

3. 最后,我们需要确保所有的任务都已经完成,所以我们需要调用ExecutorService的shutdown方法来关闭线程池。

java 复制代码
// 创建两个缓存线程池
public static ThreadFactory resizeImageThreadFactory = new ThreadFactoryBuilder()
            .setNameFormat("resizeImageThread-pool-%d")
            .build();

public static ExecutorService outerExecutor = Executors.newCachedThreadPool(resizeImageThreadFactory);

public static ExecutorService innerExecutor = Executors.newCachedThreadPool(resizeImageThreadFactory);
java 复制代码
import java.util.concurrent.*;

public class NestedLoopWithThreadPools {
    public static void main(String[] args) throws InterruptedException, ExecutionException {

        // 使用嵌套的for循环来执行操作
        for (int i = 0; i < 10; i++) {
            final int outerIndex = i;
            outerExecutor.submit(() -> {
                for (int j = 0; j < 10; j++) {
                    final int innerIndex = j;
                    innerExecutor.submit(() -> {
                        System.out.println("Outer loop index: " + outerIndex + ", Inner loop index: " + innerIndex);
                    });
                }
            });
        }

        // 确保所有的任务都已经完成
        outerExecutor.shutdown();
        innerExecutor.shutdown();
    }
}
相关推荐
码界奇点几秒前
基于Spring Boot的前后端分离商城系统设计与实现
java·spring boot·后端·java-ee·毕业设计·源代码管理
一叶飘零_sweeeet3 分钟前
深度剖析:Java 并发三大量难题 —— 死锁、活锁、饥饿全解
java·死锁·活锁·饥饿
IT乐手8 分钟前
java 对比分析对象是否有变化
android·java
云烟成雨TD13 分钟前
Spring AI Alibaba 1.x 系列【18】Hook 接口和四大抽象类
java·人工智能·spring
Hachi被抢先注册了20 分钟前
Docker学习记录
java·云原生·eureka
不会写DN1 小时前
Go 项目中 Redis 缓存的实用设计与实现(Cache-Aside 模式)
redis·缓存·golang
devilnumber1 小时前
Spring Boot 2 vs Spring Boot 3:50 条核心区别 + 升级优势 + 避坑指南
java·spring boot·springboot升级
武超杰1 小时前
Spring Cloud Alibaba Nacos 进阶:配置隔离、集群、持久化与开机自启
java·开发语言
Venhoul1 小时前
@Scheduled(cron = “1 0 0 * * ?“用法介绍
java
Rabitebla1 小时前
C++类和对象(中):默认函数 + 运算符重载 + 日期类实现完整笔记
java·开发语言·javascript