并发线程工具类分享

hi,我是阿昌,今天分享一下并发线程工具类分享可以更好的在实际项目中进行使用,废话不多说,上来先分享java类

特点

  1. 支持信号量控制并发数
  2. 支持自定义线程
  3. 简单易用
java 复制代码
@Slf4j
@Setter@Getter
public class ConcurrentExecutor<R> {


    public final ExecutorService executorService;

    /**
     * 信号量
     */
    private int permits;

    /**
     * 默认信号量大小
     */
    public static final int DEFAULT_PERMITS = 4;

    /**
     * 信号量实例
     */
    private final Semaphore semaphore;

    public static final int SEMAPHORE_TIMEOUT_MILL_SEC = 100;
    /**
     * 需要异步执行的任务
     */
    private List<R> syncExecuteResult = new ArrayList<>();

    private List<CompletableFuture<R>> futureList = new ArrayList<>();

    public ConcurrentExecutor(int permits, ExecutorService executorService) {
        this.permits = permits;
        this.semaphore = new Semaphore(permits);//并发数;控制
        this.executorService = executorService;
    }

    public static <R> ConcurrentExecutor<R> newConService(int permits, ExecutorService executorService) {
        return new ConcurrentExecutor<>(permits, executorService);
    }

    public static <R> ConcurrentExecutor<R> newConService(ExecutorService executorService) {
        return new ConcurrentExecutor<>(ConcurrentExecutor.DEFAULT_PERMITS, executorService);
    }

    /**
     * 提交单个任务
     */
    public ConcurrentExecutor<R> submit(Supplier<R> supplier) {
        boolean acquire;
        try {
            acquire = semaphore.tryAcquire(SEMAPHORE_TIMEOUT_MILL_SEC, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            acquire = false;
        }
        if (acquire) {
            CompletableFuture<R> future = CompletableFuture.supplyAsync(supplier, executorService);
            future.whenComplete((t, throwable) -> semaphore.release());
            futureList.add(future);
        } else {
            syncExecuteResult.add(supplier.get());
        }
        return this;
    }

    /**
     * 等待所有任务结束,无超时
     */
    public CompletableFuture<List<R>> invokeAllFuture() {
        return CompletableFuture.allOf(futureList.toArray(new CompletableFuture[0]))
                .thenApply(e -> futureList.stream()
                        .map(CompletableFuture::join)
                        .collect(Collectors.toList()))
                .whenComplete((rs, throwable) -> {
                    if (rs != null && syncExecuteResult != null && syncExecuteResult.size() > 0) {
                        rs.addAll(syncExecuteResult);
                    }
                });
    }

    public List<R> invokeAll() {
        return invokeAllFuture().join();
    }
}

这个工具类可以使用自定义线程池,并设置信号量各种来限制并发执行的线程数量,同时用invokeAllFuture()来让主线程阻塞,等待所有异步线程执行完毕后再执行;

使用案例:比如在多线程调用ai模型

java 复制代码
//多线程调用ai识别
ConcurrentExecutor<String> executor = new ConcurrentExecutor<>(3, ItemConstant.aiThreadPoolExecutor);
for (List<String> partList : Lists.partition(skuNameList, 5)) {
  executor.submit(() -> {
    String str = AiStrategyFactory.chatCompletions(partList);
    if (StrUtil.isNotBlank(str)) {
      System.out.println("ai调用执行结果:" + str);
    }
    return str;
  });
}
//阻塞主线程,直到所有任务完成
executor.invokeAll();
//获取到所有线程执行结果,进行结果处理
List<String> syncExecuteResult = executor.getSyncExecuteResult();
相关推荐
wang09073 小时前
自己动手写一个spring之IOC_2
java·后端·spring
来杯@Java3 小时前
学生选课管理系统(基于springboot+vue前后端分离的项目)计算机毕业设计java
java·spring boot·spring·vue·毕业设计·maven·mybatis
不知名的老吴4 小时前
线程的生命周期之线程“插队“
java·开发语言·python
ANnianStriver4 小时前
PetLumina-02-后端开发与前后端联调
java·ai·sa-token
杨了个杨89825 小时前
Keepalived + Nginx + HAProxy 高可用架构部署实战案例
java·nginx·架构
马士兵教育7 小时前
Java还有前景吗?Java+AI大模型学习路线及项目?
java·人工智能·python·学习·机器学习
snow@li8 小时前
Java:理解 Gradle / 后端项目的管家 / 打包SpringBoot 应用 / 完成编译、下载依赖、运行测试、打包 JAR/WAR / 速查表
java
云烟成雨TD8 小时前
Spring AI 1.x 系列【57】动态工具发现:Tool Search Tool
java·人工智能·spring
zfoo-framework8 小时前
[修改代码使用]codex官方app中使用中转(不需要cc-switch) 1.config.toml 2.sk方式登录
java