All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.hutool.core.thread.AsyncUtil Maven / Gradle / Ivy

Go to download

Hutool是一个小而全的Java工具类库,通过静态方法封装,降低相关API的学习成本,提高工作效率,使Java拥有函数式语言般的优雅,让Java语言也可以“甜甜的”。

There is a newer version: 5.8.34
Show newest version
package cn.hutool.core.thread;

import java.lang.reflect.UndeclaredThrowableException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * {@link CompletableFuture}异步工具类
* {@link CompletableFuture} 是 Future 的改进,可以通过传入回调对象,在任务完成后调用之 * * @author [email protected] * @since 5.7.17 */ public class AsyncUtil { /** * 等待所有任务执行完毕,包裹了异常 * * @param tasks 并行任务 * @throws UndeclaredThrowableException 未受检异常 */ public static void waitAll(CompletableFuture... tasks) { try { CompletableFuture.allOf(tasks).get(); } catch (InterruptedException | ExecutionException e) { throw new ThreadException(e); } } /** * 等待任意一个任务执行完毕,包裹了异常 * * @param 任务返回值类型 * @param tasks 并行任务 * @return 执行结束的任务返回值 * @throws UndeclaredThrowableException 未受检异常 */ @SuppressWarnings("unchecked") public static T waitAny(CompletableFuture... tasks) { try { return (T) CompletableFuture.anyOf(tasks).get(); } catch (InterruptedException | ExecutionException e) { throw new ThreadException(e); } } /** * 获取异步任务结果,包裹了异常 * * @param 任务返回值类型 * @param task 异步任务 * @return 任务返回值 * @throws RuntimeException 未受检异常 */ public static T get(CompletableFuture task) { try { return task.get(); } catch (InterruptedException | ExecutionException e) { throw new ThreadException(e); } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy