说明
1、jdk 8中引入了 completablefuture 类,实现了future和completionstage接口.
为异步编程提供了一些列方法,如supplyasync、runasync和thenapplyasync等。
2、功能是可以让两个或者多个进行运算来产生结果。
实例
/** * @author mghio * @since 2021-08-01 */public class completablefuturedemo { public static completablefuture<string> doonething() { return completablefuture.supplyasync(() -> { try { thread.sleep(2000); } catch (interruptedexception e) { e.printstacktrace(); } return doonething; }); } public static completablefuture<string> dootherthing(string parameter) { return completablefuture.supplyasync(() -> { try { thread.sleep(2000); } catch (interruptedexception e) { e.printstacktrace(); } return parameter + + dootherthing; }); } public static void main(string[] args) throws executionexception, interruptedexception { stopwatch stopwatch = new stopwatch(completablefuturedemo); stopwatch.start(); // 异步执行版本 testcompletablefuture(); stopwatch.stop(); system.out.println(stopwatch); } private static void testcompletablefuture() throws interruptedexception, executionexception { // 先执行 doonething 任务,后执行 dootherthing 任务 completablefuture<string> resultfuture = doonething().thencompose(completablefuturedemo::dootherthing); // 获取任务结果 string doonethingresult = resultfuture.get(); // 获取执行结果 system.out.println(doonething and dootherthing execute finished. result = + doonethingresult); } }
以上就是java中使用completablefuture的方法和示例的详细内容。