【SpringBoot】多线程 @EnableAsync @Async

使用多线程,往往是创建Thread,或者是实现runnable接口,用到线程池的时候还需要创建Executors,spring中有十分优秀的支持,就是注解@EnableAsync就可以使用多线程,@Async加在线程任务的方法上(需要异步执行的任务),定义一个线程任务,通过spring提供的ThreadPoolTaskExecutor就可以使用线程池

首先定义配置类
这个配置类需要实现AsyncConfiguer接口,并实现它的方法

  • 异步线程的执行者,在里面配置自动执行的东西,比如线程池参数
  • 线程异常处理
package ds.watsons.app.label.config;
import java.util.concurrent.Executor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 
@Configurable
@EnableAsync
public class TreadPoolConfigTest implements AsyncConfigurer{
 
    @Override
    public Executor getAsyncExecutor() {
        // TODO Auto-generated method stub
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池数量,方法: 返回可用处理器的Java虚拟机的数量。
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
        //最大线程数量
        executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors()*5);
        //线程池的队列容量
        executor.setQueueCapacity(Runtime.getRuntime().availableProcessors()*2);
        //线程名称的前缀
        executor.setThreadNamePrefix("this-excutor-");
        // setRejectedExecutionHandler:当pool已经达到max size的时候,如何处理新任务
        // CallerRunsPolicy:不在新线程中执行任务,而是由调用者所在的线程来执行
        //executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
    /*异步任务中异常处理*/
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        // TODO Auto-generated method stub
        return new SimpleAsyncUncaughtExceptionHandler();
    }       
}
  • 线程任务类
package ds.watsons.app.label.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
 
@Component
public class TreadTasks {
    @Async
    public void startMyTreadTask() {
        System.out.println("this is my async task");
    }
}
  • 调用异步线程任务
package ds.watsons.app.label.controller;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
 
import ds.watsons.app.label.service.TreadTasks;
 
@Controller
public class AsyncTaskUse {
    @Autowired
    private TreadTasks treadTasks;
    @GetMapping("/startMysync")
    public void useMySyncTask() {
        treadTasks.startMyTreadTask();
    }
}

请求url

/startMysync

返回结果:

this is my async task

原文地址:https://www.jianshu.com/p/a4b4f3df4992

发布了35 篇原创文章 · 获赞 33 · 访问量 4922

猜你喜欢

转载自blog.csdn.net/wkw1598727534/article/details/103667199