多线程并行

多线程并行、所有线程结束后输出任务完成

示例

java 复制代码
package com.fd;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Test3 {
    public static void main(String[] args) throws InterruptedException {
        AtomicInteger counter = new AtomicInteger(0);
        for (int i = 0; i < 20; i++) {
            final int index = i;
            ThreadPoolUtil. execute(() -> {  // 使用 lambda 表达式简化代码
                System.out.println("任务 " + index + "  执行者:  " + Thread.currentThread().getName());

                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (counter){
                    counter.addAndGet(1);
                    System.out.println("当前为: "+counter.get());
                }

            });
        }
        // 确保所有任务完成
        ThreadPoolUtil. shutdown();
        ThreadPoolUtil.threadPool. awaitTermination(1, TimeUnit.MINUTES);
        System.out.println("所有任务完成" + counter.get());

    }
}

工具类

java 复制代码
package com.fd;
import java.util.concurrent.*;

public class ThreadPoolUtil {

    private static final int CORE_POOL_SIZE = 4;
    private static final int MAX_POOL_SIZE = 10;
    private static final int QUEUE_CAPACITY = 100;
    private static final Long KEEP_ALIVE_TIME = 1L;

    public static final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
            CORE_POOL_SIZE,
            MAX_POOL_SIZE,
            KEEP_ALIVE_TIME,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(QUEUE_CAPACITY),
            new ThreadPoolExecutor.CallerRunsPolicy()
    );

    /**
     * 提交一个 Runnable 任务到线程池执行
     * @param task 要执行的任务
     */
    public static void execute(Runnable task) {
        threadPool.execute(task);
    }

    /**
     * 关闭线程池
     */
    public static void shutdown() {
        threadPool.shutdown();
    }

}
相关推荐
忧郁的Mr.Li29 分钟前
SpringBoot中实现多数据源配置
java·spring boot·后端
玄同76535 分钟前
从 0 到 1:用 Python 开发 MCP 工具,让 AI 智能体拥有 “超能力”
开发语言·人工智能·python·agent·ai编程·mcp·trae
czy878747537 分钟前
深入了解 C++ 中的 `std::bind` 函数
开发语言·c++
消失的旧时光-194342 分钟前
从 Kotlin 到 Dart:为什么 sealed 是处理「多种返回结果」的最佳方式?
android·开发语言·flutter·架构·kotlin·sealed
yq19820430115643 分钟前
静思书屋:基于Java Web技术栈构建高性能图书信息平台实践
java·开发语言·前端
一个public的class44 分钟前
你在浏览器输入一个网址,到底发生了什么?
java·开发语言·javascript
有位神秘人1 小时前
kotlin与Java中的单例模式总结
java·单例模式·kotlin
Jinkxs1 小时前
Gradle - 与Groovy/Kotlin DSL对比 构建脚本语言选择指南
android·开发语言·kotlin
&有梦想的咸鱼&1 小时前
Kotlin委托机制的底层实现深度解析(74)
android·开发语言·kotlin
golang学习记1 小时前
IntelliJ IDEA 2025.3 重磅发布:K2 模式全面接管 Kotlin —— 告别 K1,性能飙升 40%!
java·kotlin·intellij-idea