java - 使用 java 8 CompletableFuture 显示错误数据

标签 java completable-future

我写了一个简单的例子来理解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/

相关文章:

java - twitter4j 配置

java - java线程异常

java - HttpUrlConnection 方法在 Android 上始终为 GET

java - 对可完成 future 的测试总是通过

spring - CompletableFuture 是否在重新抛出异常时完成?

java - 这段代码具体是做什么的呢?我该如何改变它?

java - 当我在 JFrame 中使用 PaintComponent 时,我必须调整窗口大小才能显示它,除非我使用 pack。我该如何补救?

java - 如何在 Spring Boot 中缓存 CompletableFuture 的值

java - 在没有多线程的情况下使用 Future 有什么意义?

java - 如何在不阻塞的情况下启动 CompletableFuture 并在完成后执行某些操作?