首页 > 编程语言 > 详细

java8线程池创建并使用

时间:2021-05-26 21:22:30      阅读:22      评论:0      收藏:0      [点我收藏+]

1、创建
@Configuration
public class ThreadPoolConfig {

/**
* 创建线程池
*/
@Bean(name = "threadPool")
public ThreadPoolTaskExecutor creatPool(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(16); // 核心线程数目
executor.setMaxPoolSize(64); // 指定最大线程数
executor.setQueueCapacity(320); // 队列中最大的数目
executor.setThreadNamePrefix("taskThreadPool_"); // 线程名称前缀
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
// 对拒绝task的处理策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

executor.setKeepAliveSeconds(60); // 线程空闲后的最大存活时间

executor.initialize();
return executor;
}
}

2、使用
@Resource(name = "threadPool")
private ThreadPoolTaskExecutor threadPoolTaskExecutor;

@Test
void jiecTest(){
threadPoolTaskExecutor.execute(()->{
for(int i=1;i<=200;i++){
System.out.println("线线程1:"+i);
}
});

threadPoolTaskExecutor.execute(()->{
for(int i=200;i>0;i--){
System.out.println("线线程2:"+i);
}
});
}

 

3、提交任务

无返回值的任务使用execute(Runnable)

有返回值的任务使用submit(Runnable)

java8线程池创建并使用

原文:https://www.cnblogs.com/yebuzhiqiu/p/14813939.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!