spring boot中多线程和并发编程的实现

时间:2022-08-01 23:20:14

Spring中通过任务执行器TaskExecutor来实现多线程和并发编程。
使用ThreadPoolTaskExecutor可实现一个基于线程池的TaskExecutor。
因为实际开发中任务一般是异步的(即非阻塞的),所以要在配置类中@EnableAsync ,并在实际执行的Bean方法中使用@Async来声明这是一个异步方法。

配置类的实现:
@Configuration
@ComponentScan("com.prac.spring.task_executor")
@EnableAsync //开启异步任务支持
public class TaskExecutorConfig implements AsyncConfigurer {
    //配置类继承AsyncConfigurer接口并重写getAsyncExecutor方法,并返回ThreadPoolTaskExecutor,
    //这样我们就获得了一个基于线程池TaskExecutor
    @Override
    public Executor getAsyncExecutor(){
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(10);
        taskExecutor.setMaxPoolSize(15);
        taskExecutor.setQueueCapacity(30);
        taskExecutor.initialize();
        return taskExecutor;
    }

    /**
     * AsyncUncaughtExceptionHandler:用来处理从异步方法抛出的未被捕获的exceptions
     * An asynchronous method usually returns a Future instance that gives access to the underlying exception. When the method does not provide that return type, this handler can be used to managed such uncaught exceptions.
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler(){
        return null;

    }

}