多线程并行

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

示例

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

}
相关推荐
We་ct28 分钟前
深度剖析浏览器跨域问题
开发语言·前端·浏览器·跨域·cors·同源·浏览器跨域
身如柳絮随风扬34 分钟前
多数据源切换实战:从业务场景到3种实现方案全解析
java·分布式·微服务
skywalk816336 分钟前
在考虑双轨制,即在中文语法的基础上,加上数学公式的支持,这样像很多计算将更加简单方便,就像现在的小学数学课本里面一样,比如:定x=2*x + 1
开发语言
小书房39 分钟前
Kotlin的by
android·开发语言·kotlin·委托·by
就叫飞六吧1 小时前
QT写一个桌面程序exe并动态打包基本流程(c++)
开发语言·c++
threelab1 小时前
Three.js 代码云效果 | 三维可视化 / AI 提示词
开发语言·javascript·人工智能
Java小生不才1 小时前
Spring AI文生音
java·人工智能·spring
jinanwuhuaguo1 小时前
(第二十八篇)OpenClaw成本与感知的奇点——从“Token封建制”到“全民养虾”的本体论地基
android·人工智能·kotlin·拓扑学·openclaw
凯尔萨厮1 小时前
Springboot2.x+Thymeleaf项目创建
java
V搜xhliang02461 小时前
OpenClaw科研全场景用法:从文献到实验室的完整自动化方案
运维·开发语言·人工智能·python·算法·microsoft·自动化