• CompletableFuture 使用详解


    参考:

    1.CompletableFuture 教程

    2.CompletableFuture 使用详解

    1. 使用 runAsync() 运行异步计算

    如果你想异步的运行一个后台任务并且不想改任务返回任务东西,这时候可以使用 CompletableFuture.runAsync()方法,它持有一个Runnable 对象,并返回 CompletableFuture<Void>

    // Run a task specified by a Runnable Object asynchronously.
    CompletableFuture<Void> future = CompletableFuture.runAsync(new Runnable() {
        @Override
        public void run() {
            // Simulate a long-running Job
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
            System.out.println("I'll run in a separate thread than the main thread.");
        }
    });
    
    // Block and wait for the future to complete
    future.get()

    2. 使用 supplyAsync() 运行一个异步任务并且返回结果

    当任务不需要返回任何东西的时候, CompletableFuture.runAsync() 非常有用。但是如果你的后台任务需要返回一些结果应该要怎么样?

    CompletableFuture.supplyAsync() 就是你的选择。它持有supplier<T> 并且返回CompletableFuture<T>T 是通过调用 传入的supplier取得的值的类型。

    // Run a task specified by a Supplier object asynchronously
    CompletableFuture<String> future = CompletableFuture.supplyAsync(new Supplier<String>() {
        @Override
        public String get() {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
            return "Result of the asynchronous computation";
        }
    });
    
    // Block and get the result of the Future
    String result = future.get();
    System.out.println(result);
  • 相关阅读:
    day01-h1字体大小和文本居中
    js正则表达式中的
    js滚动分页原理
    在web.xml中设置全局编码
    C# 导出word 表格代码
    C# 创建单例
    Winform 异步调用2 时间
    Winform 异步调用
    c#中跨线程调用windows窗体控件
    C# 中的委托和事件
  • 原文地址:https://www.cnblogs.com/wytiger/p/13571717.html
Copyright © 2020-2023  润新知