使用java显示错误的数据8 CompletableFuture
问题描述:
我写了一个简单的例子来理解CompletableFuture。但是,当我在控制台上打印它。有时它只是显示“ASYN演示” 这是我的代码使用java显示错误的数据8 CompletableFuture
public class DemoAsyn extends Thread {
public static void main(String[] args) {
List<String> mailer = Arrays.asList("[email protected]", "[email protected]", "[email protected]", "[email protected]",
"[email protected]");
Supplier<List<String>> supplierMail =() -> mailer;
Consumer<List<String>> consumerMail = Mail::notifyMessage;
Function<List<String>,List<String>> funcMail = Mail::sendMessage;
CompletableFuture.supplyAsync(supplierMail).thenApply(funcMail).thenAccept(consumerMail);
System.out.println("asyn demo");
}
}
public class Mail {
public static List<String> sendMessage(List<String> notifies) {
notifies.forEach(x -> System.out.println("sent to " + x.toString()));
return notifies;
}
public static void notifyMessage(List<String> notifies) {
notifies.forEach(x -> System.out.println("notified to " + x.toString()));
}
}
答
你开始异步操作,但你不等待它完成 - 当你打印asyn demo
没有什么别的保持一个非守护线程活着,所以这个过程终止。只需等待由thenAccept
返回CompletableFuture<Void>
完成使用get()
:
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
public class Test {
public static void main(String[] args)
throws InterruptedException, ExecutionException {
List<String> mailer = Arrays.asList(
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]");
Supplier<List<String>> supplierMail =() -> mailer;
Consumer<List<String>> consumerMail = Test::notifyMessage;
Function<List<String>,List<String>> funcMail = Test::sendMessage;
CompletableFuture<Void> future = CompletableFuture
.supplyAsync(supplierMail)
.thenApply(funcMail)
.thenAccept(consumerMail);
System.out.println("async demo");
future.get();
}
private static List<String> sendMessage(List<String> notifies) {
notifies.forEach(x -> System.out.println("sent to " + x.toString()));
return notifies;
}
private static void notifyMessage(List<String> notifies) {
notifies.forEach(x -> System.out.println("notified to " + x.toString()));
}
}