Spring中线程池的使用 ThreadPoolTaskExecutor

一、配置类代码

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class g02线程 {

    @Bean("threadName")
    public ThreadPoolTaskExecutor a (){
        //spring框架 自己封装的线程
        ThreadPoolTaskExecutor thread = new ThreadPoolTaskExecutor();
        // 核心线程数量:线程池创建时候初始化的线程数
        thread.setCorePoolSize(4);

        // 最大线程数,线程池中最大的线程数,只有在缓冲队列满了额之后才会申请超过核心线程数的线程
        thread.setMaxPoolSize(10);

        // 缓冲队列,用来缓冲执行任务的队列
        thread.setQueueCapacity(10000);

        // 允许线程的空闲时间60秒,当超过核心线程出之外的线程在空闲时间到达之后被
        thread.setKeepAliveSeconds(60);

        // 线程池名的前缀,设置好了之后可以方便我们定位处理任务所在的线程池
        thread.setThreadNamePrefix("aa--");

        // 设置在关机时等待任务完成
        thread.setWaitForTasksToCompleteOnShutdown(true);
        // 该方法用来设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,以保证应用最后能够关闭,而不是阻塞住
        thread.setAwaitTerminationSeconds(60);

        // 设置抛出异常
        thread.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        // 初始化线程池
        thread.initialize();


        return thread;

    }



}

 

二、使用类代码

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class 线程池的使用 {

    @Resource(name="threadName")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    // 任务代码:模拟业务场景
    public void taskCode(String req){

        // 线程中执行的任务
        CompletableFuture<String> stringCompletableFuture = CompletableFuture.supplyAsync(() -> {
            return req + "任务代码执行中";
        }, threadPoolTaskExecutor);

        // 获取到线程中返回的数据
        try {
            String s = stringCompletableFuture.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }


}

 

posted @ 2023-04-21 15:31  向大海  阅读(160)  评论(0编辑  收藏  举报