多线程并行

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

示例

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();
    }

}
相关推荐
程序员贺加贝3 分钟前
别把 ThreadLocal 写进 Serializer:一次 SaaS 多租户 Jackson 上下文污染排查
java·spring boot
mmsx5 分钟前
Android 新闻资讯客户端实战:从零搭建一个完整的新闻 App
android·app·源码
许彰午11 分钟前
06-EaEngine调度器
java·低代码·架构
练习时长两年半的RL练习生12 分钟前
与AI对话后对 Actor-Critic 中 TD Target 的 a‘ 来源总结
开发语言·人工智能·php
十五年专注C++开发37 分钟前
100w条数据丝滑滚动!Qt Model/View 架构实战(二)
开发语言·c++·qt
卓怡学长42 分钟前
w181springboot机场乘客服务系统
java·数据库·spring boot·spring·intellij-idea
萧瑟余晖1 小时前
Java深入解析篇三十九之集成测试
java·开发语言·集成测试
skr爱码士1 小时前
06_Qt 常用数据类型与容器:QString、QList、QVector、QMap 的性能与实现分析
开发语言·c++·qt
总有刁民想爱朕ha1 小时前
零基础Python开发「图片批量转MP4视频」工具,本地离线、免费无水印
开发语言·python·音视频
l1t1 小时前
测试DuckDB luajit插件读取本地通达信文件
开发语言·数据库·duckdb