描述
提供异步处理
public class CompletableFutureTest {
@Test
public void testCreate() {
CompletableFuture<String> future = new CompletableFuture<>();
// 手工完成future
future.complete("hello,completableFuture");
try {
String s = future.get();
System.out.println(s);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
@Test
public void testRunAsync() {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
try {
// 该方法阻塞,直到future completed
Void aVoid = future.get();
System.out.println(aVoid);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
@Test
public void testSupplyAsync() {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "I finish completing";
});
if (future.isDone()) {
System.out.println("done " + future.getNow("I can`t find"));
} else {
try {
System.out.println("not done " + future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
@Test
public void testThenSupply() {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "I am a word";
}).thenApply((word) -> {
return word + ",I am a new word";
});
try {
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
@Test
public void testThenRun() {
AtomicBoolean close = new AtomicBoolean(true);
CompletableFuture future = CompletableFuture.runAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("I am a King");
}).thenRun(() -> {
System.out.println("I am a Queen");
close.set(false);
});
while (close.get()) {
}
}
}
引用
https://colobu.com/2018/03/12/20-Examples-of-Using-Java%E2%80%99s-CompletableFuture/
https://colobu.com/2016/02/29/Java-CompletableFuture/
https://mahmoudanouti.wordpress.com/2018/01/26/20-examples-of-using-javas-completablefuture/
https://juejin.im/post/5adbf8226fb9a07aac240a67