想必大家都用过Future,那么CompletableFuture在Future基础上又加了什么方法呢?
public class CompletableFutureTest extends BaseTest {
@Test
public void futureTest()
{
//这是一个很简单的使用future的例子
ExecutorService service = Executors.newCachedThreadPool();
Future future = service.submit(() -> {
//暂停两秒
Thread.sleep(2 * 1000);
return "return";
});
futureTest(future);
}
public void futureTest(Future future) {
System.out.println("doSomeThings");
try {
String rt = future.get().toString();
System.out.println(rt);
Assert.assertEquals(rt, "return");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
@Test
public void completableFutureTest()
{
//1 可以省掉线程池
//2 可以将第一个的值传递给第二个操作
CompletableFuture future = CompletableFuture.supplyAsync(() -> {
System.out.println("supplyAsync");
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("end-supplyAsync");
return "return";
});
//不关心上一步返回值
future.thenRun(() -> {
System.out.println("thenRun");
});
//无返回值
future.thenAccept((s) -> {
System.out.println("thenAccept");
});
//有返回值
future.thenApply((s) -> {
System.out.println("thenApply");
try {
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return s;
});
//两个都执行完 执行下一步 不关心结果 runAfterEither 任何一个执行都执行下一步
future.runAfterBoth(CompletableFuture.supplyAsync(() -> {
System.out.println("runAfterBoth");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "";
}), () -> System.out.println("end-runAfterBoth"));
//合并两个值 最终返回 而且两者是异步执行再合并
future.thenCombine(CompletableFuture.supplyAsync(() ->
{
System.out.println("thenCombine");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("end-thenCombine");
return "";
}), (s1, s2) -> s1 + " " + s2).
join();
//谁快用谁的结果
future.applyToEither(CompletableFuture.supplyAsync(() -> {
System.out.println("applyToEither");
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "returnEither";
}), s -> s).join();
//执行完成后执行 ,s为正常数据 t为异常数据
future.whenComplete((s, t) -> {
System.out.println("whenComplete");
System.out.println(s);
System.out.println(t);
});
//异常补偿
future.exceptionally(e -> {
System.out.println("exceptionally");
return "returnException";
});
//和whenComplete 一样 不过有返回值
CompletableFuture future1 = future.handleAsync((s, t) -> {
System.out.println("handle");
if (t != null) {
return "returnException";
}
return s + "handleAsync";
});
futureTest(future);
}
}