一,线程池的拒绝策略
Java ThreadPoolExecutor的拒绝策略CallerRunsPolicy的一个潜在的大坑_明明如月的技术博客-CSDN博客_callerrunspolicy
二,Java ThreadPoolExecutor的拒绝策略
Java ThreadPoolExecutor的拒绝策略_明明如月的技术博客-CSDN博客
三,ThreadPoolTaskExecutor和ThreadPoolExecutor区别
ThreadPoolTaskExecutor和ThreadPoolExecutor区别_背景模版-CSDN博客_threadpooltaskexecutor
四,springboot中@Async多线程注解使用
springboot中@Async多线程注解使用_背景模版-CSDN博客
①:根据当前服务器cpu内核,计算出核心线程数和最大线程数
②:用的线程池还是spring框架下的线程池ThreadPoolTaskExecutor
③:最大线程数和核心线程数这里保持一致
五,案例
SpringBoot异步多线程调用注解@Async使用和CountDownLatch配合使用案例_背景模版-CSDN博客
@Autowired
private Test test;
@Override
public List<Integer> findByMonth() {
List<Integer> list = new ArrayList<>();
for (int i =1;i<=12;i++){
int count= baseMapper.findByMonth(i);
list.add(count);
}
CountDownLatch countDownLatch = new CountDownLatch(6);
System.out.println("开始执行多线程任务1111111111:::"+System.currentTimeMillis());
for (int i =0;i<=5;i++){
test.doTaskThree(countDownLatch,i);
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程继续执行222222222222222:::::"+Thread.currentThread().getName());
return list;
@Component
public class Test {
//注意这个多线程方法的类一定要加@Component注解,拿给spring容器管理
@Async
public void doTaskThree(CountDownLatch countDownLatch,int i) {
long start = System.currentTimeMillis();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("第00" + i + "完成任务,耗时:" + (end - start) + "毫秒,线成名为::" + Thread.currentThread().getName());
countDownLatch.countDown();
}
}
还有一种就是使用多线程中带返回的 Future结果来进行主线程的控制,大概如下,可供参考。
@Async("getTaskExector")
public Future<String> doTaskThree(int i) {
long start = System.currentTimeMillis();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("第00" + i + "完成任务,耗时:" + (end - start) + "毫秒,线成名为::" + Thread.currentThread().getName());
return new AsyncResult("SUCUESS");
}
System.out.println("开始执行多线程任务1111111111:::"+System.currentTimeMillis());
List<Future<String>> list1 = new ArrayList<>();
for (int i =0;i<=5;i++){
Future<String> stringFuture = test.doTaskThree(i);
list1.add(stringFuture);
}
boolean flag = false;
while (!flag){
for (Future<String> future:list1){
try {
String s = future.get();
if (s =="成功"){
flag = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
System.out.println("主线程继续执行222222222222222:::::"+Thread.currentThread().getName());
六,CountDownLatch、Semaphone学习
CountDownLatch、Semaphone学习_chenkaibsw的专栏-CSDN博客