多线程之CompletableFuture使用

使用步骤一:在application.properties中添加线程池配置。

#ThreadPool

spring.task.pool.corePoolSize = 60

spring.task.pool.maxPoolSize = 100

spring.task.pool.keepAliveSecond = 120

spring.task.pool.queueCapacity = 5

spring.task.pool.encoding.force = true

spring.task.pool.encoding.charset = UTF-8

spring.task.pool.encoding.enabled = true

spring.task.pool.encoding.uri-encoding = UTF-8

步骤二:编写线程配置参数类TaskThreadPoolConfig。

@Component
@Data
@ConfigurationProperties(prefix = "spring.task.pool")
public class TaskThreadPoolConfig implements AsyncConfigurer{
    private int corePoolSize;
    private int maxPoolSize;
    private int keepAliveSeconds;
    private int queueCapacity;
}

步骤三:初始化线程池。

@Configuration
@EnalbeAsync
public class TaskExecutePool{
    @Autowried
    private TaskThreadPoolConfig threadPool;
    
    @Bean("myTaskAsyncPool")
    public Executor myTaskAsyncPool(){
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(threadPool.getCorePoolSize);
    executor.setMaxPoolSize(threadPool.getMaxPoolSize);
    executor.setWaitForTasksToCompleteOnShutdown(true);
    executor.setAwaitTerminationSeconds(60);
    executor.setQueueCapacity(threadPool.getQueueCapacity);
    executor.setKeepAliveSeconds(threadPool.getKeepAliveSeconds());
    executor.setThreadNamePrefix("MyExecutor---");
    //rejection-policy:当pool达到max size的时候,如何处理新任务
    //CALLER_RUNS:不在新任务中执行任务,而是由调用者所在的线程来执行
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    executor.initialize();
    return executor;  
    }
    
}

步骤四:创建异步任务。

@Slf4j
@Service
public class ThreadTask{
    @Async("myTaskAsyncPool")
    public CompletableFuture getMethod(){
        try{
            //可在此处添加业务逻辑
            sleep(3000);
        }catch(Exception e){
            e.printStackTrace();
        }
    //可传异步任务返回结果
    return CompletableFuture.completedFuture("自行传值");
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值