一直不太明白究驴,線程池在實際應(yīng)用當(dāng)中到底扮演什么樣的角色慨仿,有什么場景要用到,只有真正的項目設(shè)計的時候才能逐漸理解纳胧,實踐出真知說的就是這么個道理镰吆。
使用多線程,往往是創(chuàng)建Thread跑慕,或者是實現(xiàn)runnable接口万皿,用到線程池的時候還需要創(chuàng)建Executors,spring中有十分優(yōu)秀的支持核行,就是注解@EnableAsync就可以使用多線程牢硅,@Async加在線程任務(wù)的方法上(需要異步執(zhí)行的任務(wù)),定義一個線程任務(wù)芝雪,通過spring提供的ThreadPoolTaskExecutor就可以使用線程池
首先定義配置類
這個配置類需要實現(xiàn)AsyncConfiguer接口减余,并實現(xiàn)它的方法
- 異步線程的執(zhí)行者,在里面配置自動執(zhí)行的東西惩系,比如線程池參數(shù)
- 線程異常處理
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();
//核心線程池數(shù)量位岔,方法: 返回可用處理器的Java虛擬機的數(shù)量。
executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
//最大線程數(shù)量
executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors()*5);
//線程池的隊列容量
executor.setQueueCapacity(Runtime.getRuntime().availableProcessors()*2);
//線程名稱的前綴
executor.setThreadNamePrefix("this-excutor-");
// setRejectedExecutionHandler:當(dāng)pool已經(jīng)達到max size的時候堡牡,如何處理新任務(wù)
// CallerRunsPolicy:不在新線程中執(zhí)行任務(wù)抒抬,而是由調(diào)用者所在的線程來執(zhí)行
//executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
/*異步任務(wù)中異常處理*/
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
// TODO Auto-generated method stub
return new SimpleAsyncUncaughtExceptionHandler();
}
}
- 線程任務(wù)類
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");
}
}
- 調(diào)用異步線程任務(wù)
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
返回結(jié)果:
this is my async task