关键词:线程池,异步,有返回,等待
1、线程池配置
package com.listen.demo.config;
/**
* @author liuxd
* @version 1.0
* @date 2019-12-25 15:46
*/
import com.listen.demo.service.MyTaskServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
//@ComponentScan({"com.listen.demo"})
@EnableAsync
public class ExecutorConfig {
private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class);
@Bean
public Executor asyncServiceExecutor() {
logger.info("start asyncServiceExecutor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//配置核心线程数
executor.setCorePoolSize(5);
//配置最大线程数
executor.setMaxPoolSize(5);
//配置队列大小
executor.setQueueCapacity(99999);
//配置线程池中的线程的名称前缀
executor.setThreadNamePrefix("async-service-");
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//执行初始化
executor.initialize();
return executor;
}
@Bean
public MyTaskServer myTaskServer(){
return new MyTaskServer();
}
}
2、业务操作类
package com.listen.demo.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
/**
* @author liuxd
* @version 1.0
* @date 2019-12-25 15:48
*/
@Service
public class MyTaskServer {
@Async("asyncServiceExecutor")
public Future<Integer> asyncTask(CountDownLatch countDownLatch) throws Exception {
Thread.sleep(1000L);
countDownLatch.countDown();
return new AsyncResult<>(10);
}
@Async("asyncServiceExecutor")
public Future<Integer> asyncTask2(CountDownLatch countDownLatch) throws Exception {
Thread.sleep(2000L);
countDownLatch.countDown();
return new AsyncResult<>(20);
}
@Async("asyncServiceExecutor")
public Future<Integer> asyncTask3(CountDownLatch countDownLatch) throws Exception {
Thread.sleep(3000L);
countDownLatch.countDown();
return new AsyncResult<>(30);
}
}
3、异步+等待+有返回的测试类
package com.listen.demo;
import com.listen.demo.config.ExecutorConfig;
import com.listen.demo.service.MyTaskServer;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
/**
* @author liuxd
* @version 1.0
* @date 2019-12-25 16:03
*/
public class TestAsyncTask {
public static void main(String[] args) throws Exception {
System.out.println("主线程:" + Thread.currentThread().getName() + "开始执行调用任务...");
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ExecutorConfig.class);
MyTaskServer myTaskServer = context.getBean(MyTaskServer.class);
CountDownLatch countDownLatch = new CountDownLatch(3);
Future<Integer> future1 = myTaskServer.asyncTask(countDownLatch);
Future<Integer> future2 = myTaskServer.asyncTask2(countDownLatch);
Future<Integer> future3 = myTaskServer.asyncTask3(countDownLatch);
countDownLatch.await();
Integer num1 = future1.get();
Integer num2 = future2.get();
Integer num3 = future3.get();
int data = num1 + num2 + num3;
System.out.println("最终汇总计算结果:" + data);
context.close();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程:" + Thread.currentThread().getName() + "程序结束!!");
}
}