CompletableFuture+线程池+semaphore限流

package com.june;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author
 * @date 2025/4/22 15:55
 */
public class CompletableTask {

    private static final int PROCESSORS = Runtime.getRuntime().availableProcessors();
    //semaphore≤ maxCore+queue 限流
    private static final Semaphore semaphore = new Semaphore(PROCESSORS);

    public static void main(String[] args) {
        ThreadPoolExecutor executorService = new ThreadPoolExecutor(
                PROCESSORS,
                PROCESSORS * 2,
                60,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>((2*PROCESSORS)+10),
                new ThreadPoolExecutor.CallerRunsPolicy() // CallerRunsPolicy
        );
        RejectedExecutionHandler originalHandler = executorService.getRejectedExecutionHandler();

        executorService.setRejectedExecutionHandler((r, e) -> {
            System.out.println("任务被拒绝");
            originalHandler.rejectedExecution(r, e); // 调用原始的 CallerRunsPolicy
        });

        List> collect = IntStream.range(0, 100)
                .mapToObj(e -> {
                    CompletableFuture integerCompletableFuture = null;
                    try {
                        semaphore.acquire();
                        integerCompletableFuture = doFuture(executorService);
                        integerCompletableFuture.whenComplete((r, ex) -> {
                            semaphore.release();
                        });
                    } catch (Exception ex) {
                        semaphore.release();
                        System.out.println(ex.getMessage());
                    }
                    return integerCompletableFuture;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        List res = collect.stream().map(CompletableFuture::join).collect(Collectors.toList());

        executorService.shutdown();

        System.out.println((Integer) res.stream().mapToInt(Integer::intValue).sum());

    }

    private static CompletableFuture doFuture(ExecutorService executorService) {
        //                    System.out.println("task is completed,exception");
        return CompletableFuture.supplyAsync(() -> {
                    try {
                        TimeUnit.MILLISECONDS.sleep(1000);
                    } catch (InterruptedException e) {
                        System.out.println(e.getMessage());
                    }
                    System.out.println(Thread.currentThread().getName());
                    return 1;
                }, executorService)
                .whenComplete((v, e) -> {
                    if (e != null)
                        System.out.println("task is completed,no exception");
                })
                .exceptionally(e -> {
//                    System.out.println("task is completed,exception");
                    return 0;
                });
    }

}

你可能感兴趣的:(java)