多线程并行

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

示例

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

}
相关推荐
better_liang12 小时前
每日Java面试场景题知识点之-分布式事务处理
java·微服务·面试·springcloud·分布式事务
执笔论英雄12 小时前
Slime异步原理(单例设计模式)4
开发语言·python·设计模式
L***d67014 小时前
Spring Boot 各种事务操作实战(自动回滚、手动回滚、部分回滚)
java·数据库·spring boot
e***749514 小时前
Modbus报文详解
服务器·开发语言·php
凌波粒14 小时前
Springboot基础教程(3)--自动装配原理/静态资源处理/欢迎页
java·spring boot·后端
lly20240614 小时前
ASP 发送电子邮件详解
开发语言
小徐敲java14 小时前
python使用s7协议与plc进行数据通讯(HslCommunication模拟)
开发语言·python
likuolei14 小时前
XSL-FO 软件
java·开发语言·前端·数据库
凌波粒14 小时前
SpringBoot基础教程(2)--yaml/配置文件注入/数据校验/多环境配置
java·spring boot·后端·spring
6***379414 小时前
PHP在电商中的BigCommerce
开发语言·php