zoukankan      html  css  js  c++  java
  • Java异步CompletableFuture的使用

      所谓异步调用其实就是实现一个可无需等待被调用函数的返回值而让操作继续运行的方法。Java中的CompletableFuture 提供了四个静态方法来创建一个异步操作。

    1 public static CompletableFuture<Void> runAsync(Runnable runnable)
    2 public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)
    3 public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
    4 public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)

      没有指定Executor的方法会使用ForkJoinPool.commonPool() 作为它的线程池执行异步代码。如果指定线程池,则使用指定的线程池运行。其中:

      runAsync方法不支持返回值。

      supplyAsync可以支持返回值。

      如下:

    //无返回值
    public static void runAsync() throws Exception {
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            try {
                System.out.println("run start ...");
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
            }
            System.out.println("run end ...");
        });
        
        future.get();
    }
    
    //有返回值
    public static void supplyAsync() throws Exception {         
        CompletableFuture<Long> future = CompletableFuture.supplyAsync(() -> {
            try {
                System.out.println("run start ...");
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
            }
            System.out.println("run end ...");
            return System.currentTimeMillis();
        });
    
        long time = future.get();
        System.out.println("time = "+time);
    }

      今天写到这里,简单的使用如上代码,后续会有更新。

  • 相关阅读:
    JavaScript 高级
    JavaScript 归纳
    完全二叉树, 最大堆 , 堆排序
    二叉树
    Java秒杀系统方案优化 高性能高并发实战(1)
    精选 SQL 脚本
    树形结构有关的SQL
    在Sql server数据库中,关于触发器的创建、调用及删除
    SQLServer 唯一键约束和唯一索引有什么区别?
    很不错的 VBA 网址
  • 原文地址:https://www.cnblogs.com/JohanChan/p/11251080.html
Copyright © 2011-2022 走看看