一、ThreadPoolExecutor------线程池
private static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(30, 30, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(60), new ThreadPoolExecutor.AbortPolicy());
static { threadPoolExecutor.allowCoreThreadTimeOut(true); }
System.out.println("======start======="); threadPoolExecutor.execute(() -> { System.out.println("============="); }); System.out.println("=========end========");
//异步执行操作
参考资料:https://blog.csdn.net/qq_25806863/article/details/71126867
二、CompletableFuture----获取结果
CompletableFuture<Integer> result = CompletableFuture.supplyAsync(() -> {C System.out.println("==========2========="); return 1; }); CompletableFuture<Integer> res = CompletableFuture.supplyAsync(() -> { return 2; });
Integer x = result.get();
Integer y = res.get();
三、异步工具类
public interface AsyncToolCommon { /** * 异步执行一个无参无返回值的方法 * @param voidFunction * @throws Exception */ void asyncFunction(VoidFunction voidFunction); /** * 异步执行一个无参有返回值的方法 * @param supplier */ <T> void asyncSupplier(Supplier<T> supplier); }
@Service public class AsyncToolCommonImpl implements AsyncToolCommon { private static final Logger logger = LoggerFactory.getLogger(AsyncToolCommonImpl.class); private static final ForkJoinPool forkJoinPool = new ForkJoinPool(2 * Runtime.getRuntime().availableProcessors() + 1); /** * 异步执行一个无参无返回值的方法 * * @param voidFunction * @throws Exception */ @Override public void asyncFunction(VoidFunction voidFunction) { CompletableFuture.supplyAsync(() -> { try { voidFunction.execute(); return ResultEnum.SUCCESS.getCode(); } catch (Exception e) { logger.error("asyncExecute error:{}", e); throw new RuntimeException(e); } }, forkJoinPool); } /** * 异步执行一个无参有返回值的方法 * * @param supplier */ @Override public <T> void asyncSupplier(Supplier<T> supplier) { CompletableFuture.supplyAsync(() -> supplier.get(), forkJoinPool); } }
@FunctionalInterface public interface VoidFunction { /** * 无参构造体 */ void execute() throws Exception; }
asyncToolCommon.asyncFunction(() -> .....);
四、循环调用
List<CompletableFuture<Integer>> futureList = Lists.newArrayList(); for(int i=0;i<10;i++){ futureList.add(CompletableFuture.supplyAsync(() -> {C System.out.println("==========2========="); return 1; });) }
int count = 0; for (CompletableFuture<Integer> future : futureList) { Integer i = future.get(600, TimeUnit.MILLISECONDS); count += i; }
五、Fork/Join
//线程池 private ForkJoinPool facePlatFormForkJoinPool = new ForkJoinPool(20); private ForkJoinPool faceInfoForkJoinPool = new ForkJoinPool(20);
Callable<SearchResultJson> facePlatformCallable = () -> faceService.search(img, searchReq.getClientName(), searchReq.getClientIp(), finalAppSecret, finalToken); //回调执行结果 Future<SearchResultJson> facePlatFormFuture =facePlatFormForkJoinPool.submit(facePlatformCallable); SearchResultJson facePlatFormResp = facePlatFormFuture.get(6000, TimeUnit.MILLISECONDS); Callable<Response<FaceInfoResult>> faceInfoCallable = () -> faceJsfService.getFaceInfo(faceInfoParam); Future<Response<FaceInfoResult>> faceInfoFuture = faceInfoForkJoinPool.submit(faceInfoCallable); Response<FaceInfoResult> faceInfoResp = faceInfoFuture.get(6000, TimeUnit.MILLISECONDS);