线程池使用例子
package com.chen.hi.test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class ThreadPoolExecutorTest {
class Task implements Callable<String> {
private String taskProperty;
public Task(String taskProperty) {
this.taskProperty = taskProperty;
}
@Override
public String call() throws InterruptedException {
Thread.sleep(1000);
System.out.println("完成:" + taskProperty);
return "返回值:" + taskProperty;
}
}
public void start() throws ExecutionException, InterruptedException {
//创建线程池,并发量最大为5,因为是linked,所以队列不会满
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
5, 10,
1, TimeUnit.SECONDS,
new LinkedBlockingDeque<>(),
new ThreadPoolExecutor.CallerRunsPolicy());
//用于存储线程的返回值
List<Future<String>> results = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Task task = new Task(String.valueOf(i));
System.out.println("放入线程池:" + i);
//调用submit可以获得线程的返回值
Future<String> result = threadPoolExecutor.submit(task);
//execute直接进行异步,不获得返回值
int finalI = i;
threadPoolExecutor.execute(() -> threadPoolDo(String.valueOf(finalI)));
results.add(result);
}
//此函数表示不再接收新任务,
//如果不调用,awaitTermination将一直阻塞
threadPoolExecutor.shutdown();
//1天,模拟永远等待
System.out.println(threadPoolExecutor.awaitTermination(1, TimeUnit.DAYS));
//输出结果
for (int i = 0; i < 10; i++) {
System.out.println(results.get(i).get());
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
ThreadPoolExecutorTest test = new ThreadPoolExecutorTest();
test.start();
}
private void threadPoolDo(String name) {
System.out.println("执行直接异步任务:" + name);
}
}
spring boot下如何使用
这边我使用伪代码展示,因为spring cloud相关配置什么得比较麻烦
@Component
public class TestService {
//线程池
private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1000));
//某个需要应用的其他spring cloud服务
@Resource
private OtherService otherService;
public String getResult(TestReuquest rq) throws ExecutionException, InterruptedException {
List<Future<String>> resultDOList = new ArrayList<>();
//调用其他微服务
for (int i = 0; i < 10; i++) {
//不需要结果值得异步
int finalI = i;
threadPoolExecutor.execute(() -> threadPoolDo(String.valueOf(finalI)));
//需要结果值得异步
Task task = new Task(String.valueOf(i));
Future<String> future = threadPoolExecutor.submit(task);
resultDOList.add(future);
}
for (Future<String> future : resultDOList) {
//获得微服务的结果值
String result = future.get();
}
return "true";
}
private void threadPoolDo(String name) {
otherService.doSomeThing(name);
}
//注意Callable中的string就是返回的结果值
class Task implements Callable<String> {
private String taskProperty;
public Task(String taskProperty) {
this.taskProperty = taskProperty;
}
@Override
public String call() throws Exception {
String result = otherService.doSomeThing(taskProperty);
return result;
}
}
}