我写了一个简单的例子来理解CompletableFuture。但是当我在控制台上打印它时。有时它只显示“asyn demo” 这是我的代码
public class DemoAsyn extends Thread {
public static void main(String[] args) {
List<String> mailer = Arrays.asList("bach1@gmail.com", "bach2@gmail.com", "bach3@gmail.com", "bach4@gmail.com",
"bach5@gmail.com");
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
时没有其他任何东西可以使非守护线程保持 Activity 状态,因此进程终止。只需等待 CompletableFuture<Void>
返回者 thenAccept
完成使用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(
"bach1@gmail.com",
"bach2@gmail.com",
"bach3@gmail.com",
"bach4@gmail.com",
"bach5@gmail.com");
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()));
}
}
关于java - 使用 java 8 CompletableFuture 显示错误数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40715385/