直接上代码
线程配置类
package zengmg.nbpi.com.thread;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;import java.util.concurrent.Executor;/*** @Auther 松门一枝花* @Date 2020/5/28*/
@Configuration
@EnableAsync // 启用异步任务
public class AsyncConfiguration {// 声明一个线程池(并指定线程池的名字)@Bean("nbpiTaskExecutor")public Executor asyncExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();//核心线程数:线程池创建时候初始化的线程数executor.setCorePoolSize(5);//最大线程数:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程executor.setMaxPoolSize(500);//允许线程的空闲时间60秒:当超过了核心线程出之外的线程在空闲时间到达之后会被销毁executor.setKeepAliveSeconds(60);//线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池executor.setThreadNamePrefix("DailyAsync-");executor.initialize();return executor;}
}
服务类
package zengmg.nbpi.com.thread;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;/*** @Auther 松门一枝花* @Date 2020/5/28*/
@Service
public class CustomMultiThreadingService {private static final Logger logger = LoggerFactory.getLogger(CustomMultiThreadingService.class);/*如何让异步调用的执行任务使用这个线程池中的资源来运行呢?方法非常简单,我们只需要在@Async注解中指定线程池名即可*/@Async("nbpiTaskExecutor")public void executeAysncTask(Integer i) throws InterruptedException {logger.info("CustomMultiThreadingService ==> executeAysncTask1 method: 执行异步任务{} ", i);Thread.sleep(500L);}}
控制类
package zengmg.nbpi.com.thread;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;/*** @Auther 松门一枝花* @Date 2020/5/28*/
@Controller
@RequestMapping(value="/multithreading")
public class CustomMultiThreadingController {@Autowiredprivate CustomMultiThreadingService customMultiThreadingService;@ResponseBody@RequestMapping("/dotask")public String doTask() {try {for (int i=0;i<100000;i++){customMultiThreadingService.executeAysncTask(i);}} catch (InterruptedException e) {e.printStackTrace();}return "success";}}
运行效果
异步方法和调用方法一定要写在不同的类中
,如果写在一个类中,是没有效果的!