使用线程池简单用法
作者:互联网
1.springboot
配置
@EnableAsync // 启用 Spring 的异步方法执行功能 @Configuration public class ExecutorConfig {
@Bean("asyncExecutor")
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 配置核心线程数量
executor.setCorePoolSize(3);
// 配置最大线程数
executor.setMaxPoolSize(5);
// 配置队列容量
executor.setQueueCapacity(1);
// 配置空闲线程存活时间
executor.setKeepAliveSeconds(60);
executor.setAllowCoreThreadTimeOut(false);
// 设置拒绝策略,直接在execute方法的调用线程中运行被拒绝的任务
executor.setRejectedExecutionHandler(new org.apache.tomcat.util.threads.ThreadPoolExecutor.CallerRunsPolicy());
// 执行初始化
executor.initialize();
return executor;
}
}
service
@Service @RequiredArgsConstructor(onConstructor_ = {@Autowired}) @Slf4j public class TestService { @Async("asyncExecutor") public void test() { try { for (int i = 0; i <11 ; i++) { log.info("{}",i); Thread.sleep(1000); } } catch (InterruptedException e) { e.printStackTrace(); } } }
controller
@Slf4j
@Validated
@RestController
@RequestMapping("/remote")
@Api(tags = "远程调用管理")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class RemoteController {
@Autowired private TestService testService; @PostMapping("/test") @ApiOperation("测试") public Result test() { testService.test(); return Result.ok(); }
}
结果,调用成功了,但是后台还在异步执行程序。
2.jfinal
启动后就设置线程,并且设置全局变量。
@Override public void afterJFinalStart() { //重新解析未知的知识点 //TimerManager.AnalysisTimerManager(false); //TimerManager.AutomatiParsingManager(false); //TimerManager.wikiTimerManager(false); ScheduledExecutorService service = new ScheduledThreadPoolExecutor(1,new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build()); service.scheduleAtFixedRate(new TypeTemplateService(), 1, 10, TimeUnit.MINUTES); //设置线程池 ThreadFactory namedThreadFactory = new ThreadFactoryBuilder() .setNameFormat("demo-pool-%d").build(); ExecutorService singleThreadPool = new ThreadPoolExecutor(5, Integer.MAX_VALUE, 60L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy()); ServletContext servletContext= JFinal.me().getServletContext() ; servletContext.setAttribute("singleThreadPool",singleThreadPool); }
使用
public class CommonController extends Controller { /** * @Author coco * @Description //线程池的使用案例。 * @Date 2022/7/20 15:38 **/ public void test(){
//获取全局变量 ServletContext servletContext= JFinal.me().getServletContext() ; ExecutorService singleThreadPool= (ExecutorService) servletContext.getAttribute("singleThreadPool"); System.out.println(singleThreadPool); singleThreadPool.execute(()->{ for (int i = 0; i < 10; i++) { System.out.println("test1"+i); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } }); renderJson(MsgUtil.successMsg("test1")); } }
结果,调用成功了,但是后台还在异步执行程序。
标签:executor,singleThreadPool,用法,线程,简单,test,new,public 来源: https://www.cnblogs.com/MetaVers/p/16559763.html