1.接口调用线程池类
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.task.TaskRejectedException;
import java.util.concurrent.*;
/**
* 远程接口调用线程池 帮助类
*
*/
public class ThreadPoolSupport {
private static final Logger logger = LoggerFactory.getLogger(ThreadPoolSupport.class);
/**
* 14 * 自定义线程名称,方便的出错的时候溯源
* 15
*/
private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("thread-pool-%d").build();
/**
* 19 * corePoolSize 线程池核心池的大小
* 20 * maximumPoolSize 线程池中允许的最大线程数量
* 21 * keepAliveTime 当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间
* 22 * unit keepAliveTime 的时间单位
* 23 * workQueue 用来储存等待执行任务的队列
* 24 * threadFactory 创建线程的工厂类
* 25 * handler 拒绝策略类,当线程池数量达到上线并且workQueue队列长度达到上限时就需要对到来的任务做拒绝处理
* 26
*/
private static ExecutorService service = new ThreadPoolExecutor(
20,
20,
10L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(4096),
namedThreadFactory,
new ThreadPoolExecutor.CallerRunsPolicy()
);
/**
* 38 * 获取线程池
* 39 * @return 线程池
* 40
*/
public static ExecutorService getEs() {
return service;
}
/**
* 46 * 使用线程池创建线程并异步执行任务
* 47 * @param r 任务
* 48
*
* @return
*/
public static <T> Future<T> newTask(Callable<T> task) {
try {
return service.submit(task);
} catch (RejectedExecutionException var4) {
throw new TaskRejectedException("Executor [" + service + "] did not accept task: " + task, var4);
}
}
public static Future<?> newTask(Runnable r) {
return service.submit(r);
}
}
2.List<CompletableFuture<Void>>使用
Map<String, String> contextMap = MDC.getCopyOfContextMap();
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (int i = 0; i < 100; i++) { //假定这里执行100次
futures.add(CompletableFuture.runAsync(() -> {
MDC.setContextMap(contextMap);
{/*需要执行的代码逻辑*/}
}, ThreadPoolRemoteServiceSupport.getEs()));//在线程池内获取线程异步执行任务
}
CompletableFuture[] completableFutures = futures.toArray(new CompletableFuture[0]);
log.debug("completableFutures size:{}", completableFutures.length);
/*等待执行completableFutures完再执行,allOf()会在通用池中的线程中异步地执行。所以我们需要调用join方法等待它完成*/
CompletableFuture.allOf(completableFutures).join();
3.从线程池内获取线程异步执行任务
ThreadPoolSupport.newTask(() -> {执行代码...});