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


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;

    }

}



转载于:https://www.cnblogs.com/brucehan/p/11038711.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值