zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    python基础--文件操作实现全文或单行替换
    python基础7--集合
    python读写json文件
    python基础6--目录结构
    python基础5--模块
    Ubuntu的一些常用快捷键
    ubuntu dpkg 命令详解
    linux(Ubuntu)安装QQ2013
    fcitx-sogoupinyin下载地址和安装
    Ubuntu下装QQ2014
  • 原文地址:https://www.cnblogs.com/wytiger/p/13571717.html
Copyright © 2011-2022 走看看