学会 CompletableFuture:让你的代码免受阻塞之苦!

(Linux)DHCP 超级作用域和中继代理(超难受做了超久) DHCP服务器在192.168.159.0 可以实现分配IP的功能,现在要跨网段分配IP 就需要用到DHCP中继代理。中继代理有两张网卡分别eth0:IP 192.168.159.2 ;eth1: IP:192.168.200.2 。现在要实现192.168.200.0网段的客户机可以获取DHCP服务器的IP。中继代理其实是相当于一个路由器的作用 DHCP服务器的IP地址 :192.168.159... 阅读详情

👉 这是一个或许对你有用的社群

🐱 一对一交流/面试小册/简历优化/求职解惑,欢迎加入「芋道快速开发平台」知识星球。下面是星球提供的部分资料: 

81502ed52151f61d61cb81807afb4d30.gif

👉这是一个或许对你有用的开源项目

国产 Star 破 10w+ 的开源项目,前端包括管理后台 + 微信小程序,后端支持单体和微服务架构。

功能涵盖 RBAC 权限、SaaS 多租户、数据权限、商城、支付、工作流、大屏报表、微信公众号等等功能:

  • Boot 地址:https://gitee.com/zhijiantianya/ruoyi-vue-pro

  • Cloud 地址:https://gitee.com/zhijiantianya/yudao-cloud

  • 视频教程:https://doc.iocoder.cn

来源:juejin.cn/post/
6844904024332828685

3111e65f1bea5a9309a2da2f23f88c2d.jpeg


写在前面

通过阅读本篇文章你将了解到:

  • CompletableFuture的使用

  • CompletableFure异步和同步的性能测试

  • 已经有了Future为什么仍需要在JDK1.8中引入CompletableFuture

  • CompletableFuture的应用场景

  • 对CompletableFuture的使用优化

基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://github.com/YunaiV/ruoyi-vue-pro

  • 视频教程:https://doc.iocoder.cn/video/

场景说明

查询所有商店某个商品的价格并返回,并且查询商店某个商品的价格的API为同步 一个Shop类,提供一个名为getPrice的同步方法

  • 店铺类:Shop.java

public class Shop {
    private Random random = new Random();
    /**
     * 根据产品名查找价格
     * */
    public double getPrice(String product) {
        return calculatePrice(product);
    }

    /**
     * 计算价格
     *
     * @param product
     * @return
     * */
    private double calculatePrice(String product) {
        delay();
        //random.nextDouble()随机返回折扣
        return random.nextDouble() * product.charAt(0) + product.charAt(1);
    }

    /**
     * 通过睡眠模拟其他耗时操作
     * */
    private void delay() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

查询商品的价格为同步方法,并通过sleep方法模拟其他操作。这个场景模拟了当需要调用第三方API,但第三方提供的是同步API,在无法修改第三方API时如何设计代码调用提高应用的性能和吞吐量,这时候可以使用CompletableFuture类

基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://github.com/YunaiV/yudao-cloud

  • 视频教程:https://doc.iocoder.cn/video/

CompletableFuture使用

Completable是Future接口的实现类,在JDK1.8中引入

  • CompletableFuture的创建:

    说明:

    CompletableFuture<Double> futurePrice = new CompletableFuture<>();
    public static <U> CompletableFuture<U> completedFuture(U value) {
        return new CompletableFuture<U>((value == null) ? NIL : value);
    }

    参数的值为任务执行完的结果,一般该方法在实际应用中较少应用

    //方法一
    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
        return asyncSupplyStage(asyncPool, supplier);
    }
    //方法二
    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,
                                                       Executor executor) {
        return asyncSupplyStage(screenExecutor(executor), supplier);
    }
    //方法一
    public static CompletableFuture<Void> runAsync(Runnable runnable) {
        return asyncRunStage(asyncPool, runnable);
    }
    //方法二
    public static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor) {
        return asyncRunStage(screenExecutor(executor), runnable);
    }
    • 使用CompletableFuture#runAsync静态方法创建 runAsync有两个重载方法

    • 使用 CompletableFuture#supplyAsync静态方法创建 supplyAsync有两个重载方法:

    • 使用CompletableFuture#completedFuture静态方法创建

    • 两个重载方法之间的区别 => 后者可以传入自定义Executor,前者是默认的,使用的ForkJoinPool

    • supplyAsync和runAsync方法之间的区别 => 前者有返回值,后者无返回值

    • Supplier是函数式接口,因此该方法需要传入该接口的实现类,追踪源码会发现在run方法中会调用该接口的方法。因此使用该方法创建CompletableFuture对象只需重写Supplier中的get方法,在get方法中定义任务即可。又因为函数式接口可以使用Lambda表达式,和new创建CompletableFuture对象相比代码会简洁 不少

    • 使用new方法

  • 结果的获取: 对于结果的获取CompltableFuture类提供了四种方式

    //方式一
    public T get()
    //方式二
    public T get(long timeout, TimeUnit unit)
    //方式三
    public T getNow(T valueIfAbsent)
    //方式四
    public T join()

    说明:

    示例:

    • get()和get(long timeout, TimeUnit unit) => 在Future中就已经提供了,后者提供超时处理,如果在指定时间内未获取结果将抛出超时异常

    • getNow => 立即获取结果不阻塞,结果计算已完成将返回结果或计算过程中的异常,如果未计算完成将返回设定的valueIfAbsent值

    • join => 方法里不会抛出异常

public class AcquireResultTest {
  public static void main(String[] args) throws ExecutionException, InterruptedException {
      //getNow方法测试
      CompletableFuture<String> cp1 = CompletableFuture.supplyAsync(() -> {
          try {
              Thread.sleep(60 * 1000 * 60 );
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
  
          return "hello world";
      });
  
      System.out.println(cp1.getNow("hello h2t"));
  
      //join方法测试
      CompletableFuture<Integer> cp2 = CompletableFuture.supplyAsync((()-> 1 / 0));
      System.out.println(cp2.join());
  
      //get方法测试
      CompletableFuture<Integer> cp3 = CompletableFuture.supplyAsync((()-> 1 / 0));
      System.out.println(cp3.get());
  }
}

说明:

  • 第一个执行结果为hello h2t,因为要先睡上1分钟结果不能立即获取

  • join方法获取结果方法里不会抛异常,但是执行结果会抛异常,抛出的异常为CompletionException

  • get方法获取结果方法里将抛出异常,执行结果抛出的异常为ExecutionException

  • 异常处理: 使用静态方法创建的CompletableFuture对象无需显示处理异常,使用new创建的对象需要调用completeExceptionally方法设置捕获到的异常,举例说明:

CompletableFuture completableFuture = new CompletableFuture();
new Thread(() -> {
   try {
       //doSomething,调用complete方法将其他方法的执行结果记录在completableFuture对象中
       completableFuture.complete(null);
   } catch (Exception e) {
       //异常处理
       completableFuture.completeExceptionally(e);
    }
}).start();

同步方法Pick异步方法查询所有店铺某个商品价格

店铺为一个列表:

private static List<Shop> shopList = Arrays.asList(
        new Shop("BestPrice"),
        new Shop("LetsSaveBig"),
        new Shop("MyFavoriteShop"),
        new Shop("BuyItAll")
);

同步方法:

private static List<String> findPriceSync(String product) {
    return shopList.stream()
            .map(shop -> String.format("%s price is %.2f",
                    shop.getName(), shop.getPrice(product)))  //格式转换
            .collect(Collectors.toList());
}

异步方法:

private static List<String> findPriceAsync(String product) {
    List<CompletableFuture<String>> completableFutureList = shopList.stream()
            //转异步执行
            .map(shop -> CompletableFuture.supplyAsync(
                    () -> String.format("%s price is %.2f",
                            shop.getName(), shop.getPrice(product))))  //格式转换
            .collect(Collectors.toList());

    return completableFutureList.stream()
            .map(CompletableFuture::join)  //获取结果不会抛出异常
            .collect(Collectors.toList());
}

性能测试结果:

Find Price Sync Done in 4141
Find Price Async Done in 1033

异步 执行效率提高四倍

为什么仍需要CompletableFuture

在JDK1.8以前,通过调用线程池的submit方法可以让任务以异步的方式运行,该方法会返回一个Future对象,通过调用get方法获取异步执行的结果:

private static List<String> findPriceFutureAsync(String product) {
    ExecutorService es = Executors.newCachedThreadPool();
    List<Future<String>> futureList = shopList.stream().map(shop -> es.submit(() -> String.format("%s price is %.2f",
            shop.getName(), shop.getPrice(product)))).collect(Collectors.toList());

    return futureList.stream()
            .map(f -> {
                String result = null;
                try {
                    result = f.get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }

                return result;
            }).collect(Collectors.toList());
}

既生瑜何生亮,为什么仍需要引入CompletableFuture?对于简单的业务场景使用Future完全没有,但是想将多个异步任务的计算结果组合起来,后一个异步任务的计算结果需要前一个异步任务的值等等,使用Future提供的那点API就囊中羞涩,处理起来不够优雅,这时候还是让CompletableFuture以声明式 的方式优雅的处理这些需求。而且在Future编程中想要拿到Future的值然后拿这个值去做后续的计算任务,只能通过轮询的方式去判断任务是否完成这样非常占CPU并且代码也不优雅,用伪代码表示如下:

while(future.isDone()) {
    result = future.get();
    doSomrthingWithResult(result);
}

但CompletableFuture提供了API帮助我们实现这样的需求

其他API介绍

whenComplete计算结果的处理:

对前面计算结果进行处理,无法返回新值 提供了三个方法:

//方法一
public CompletableFuture<T> whenComplete(BiConsumer<? super T,? super Throwable> action)
//方法二
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action)
//方法三
public CompletableFuture<T> whenCompleteAsync(BiConsumer<? super T,? super Throwable> action, Executor executor)

说明:

  • BiFunction<? super T,? super U,? extends V> fn参数 => 定义对结果的处理

  • Executor executor参数 => 自定义线程池

  • 以async结尾的方法将会在一个新的线程中执行组合操作

示例:

public class WhenCompleteTest {
    public static void main(String[] args) {
        CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> "hello");
        CompletableFuture<String> cf2 = cf1.whenComplete((v, e) ->
                System.out.println(String.format("value:%s, exception:%s", v, e)));
        System.out.println(cf2.join());
    }
}
thenApply转换:

将前面计算结果的的CompletableFuture传递给thenApply,返回thenApply处理后的结果。可以认为通过thenApply方法实现CompletableFuture<T>至CompletableFuture<U>的转换。白话一点就是将CompletableFuture的计算结果作为thenApply方法的参数,返回thenApply方法处理后的结果 提供了三个方法:

//方法一
public <U> CompletableFuture<U> thenApply(
    Function<? super T,? extends U> fn) {
    return uniApplyStage(null, fn);
}

//方法二
public <U> CompletableFuture<U> thenApplyAsync(
    Function<? super T,? extends U> fn) {
    return uniApplyStage(asyncPool, fn);
}

//方法三
public <U> CompletableFuture<U> thenApplyAsync(
    Function<? super T,? extends U> fn, Executor executor) {
    return uniApplyStage(screenExecutor(executor), fn);
}

说明:

  • Function<? super T,? extends U> fn参数 => 对前一个CompletableFuture 计算结果的转化操作

  • Executor executor参数 => 自定义线程池

  • 以async结尾的方法将会在一个新的线程中执行组合操作 示例:

public class ThenApplyTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> result = CompletableFuture.supplyAsync(ThenApplyTest::randomInteger).thenApply((i) -> i * 8);
        System.out.println(result.get());
    }

    public static Integer randomInteger() {
        return 10;
    }
}

这里将前一个CompletableFuture计算出来的结果扩大八倍

thenAccept结果处理:

thenApply也可以归类为对结果的处理,thenAccept和thenApply的区别就是没有返回值 提供了三个方法:

//方法一
public CompletableFuture<Void> thenAccept(Consumer<? super T> action) {
    return uniAcceptStage(null, action);
}

//方法二
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action) {
    return uniAcceptStage(asyncPool, action);
}

//方法三
public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action,
                                               Executor executor) {
    return uniAcceptStage(screenExecutor(executor), action);
}

说明:

  • Consumer<? super T> action参数 => 对前一个CompletableFuture计算结果的操作

  • Executor executor参数 => 自定义线程池

  • 同理以async结尾的方法将会在一个新的线程中执行组合操作 示例:

public class ThenAcceptTest {
    public static void main(String[] args) {
        CompletableFuture.supplyAsync(ThenAcceptTest::getList).thenAccept(strList -> strList.stream()
                .forEach(m -> System.out.println(m)));
    }

    public static List<String> getList() {
        return Arrays.asList("a", "b", "c");
    }
}

将前一个CompletableFuture计算出来的结果打印出来

thenCompose异步结果流水化:

thenCompose方法可以将两个异步操作进行流水操作 提供了三个方法:

//方法一
public <U> CompletableFuture<U> thenCompose(
    Function<? super T, ? extends CompletionStage<U>> fn) {
    return uniComposeStage(null, fn);
}

//方法二
public <U> CompletableFuture<U> thenComposeAsync(
    Function<? super T, ? extends CompletionStage<U>> fn) {
    return uniComposeStage(asyncPool, fn);
}

//方法三
public <U> CompletableFuture<U> thenComposeAsync(
    Function<? super T, ? extends CompletionStage<U>> fn,
    Executor executor) {
    return uniComposeStage(screenExecutor(executor), fn);
}

说明:

  • Function<? super T, ? extends CompletionStage<U>> fn参数 => 当前CompletableFuture计算结果的执行

  • Executor executor参数 => 自定义线程池

  • 同理以async结尾的方法将会在一个新的线程中执行组合操作 示例:

public class ThenComposeTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> result = CompletableFuture.supplyAsync(ThenComposeTest::getInteger)
                .thenCompose(i -> CompletableFuture.supplyAsync(() -> i * 10));
        System.out.println(result.get());
    }

    private static int getInteger() {
        return 666;
    }

    private static int expandValue(int num) {
        return num * 10;
    }
}

执行流程图:

ca1e39bd0283c571d7055d59a5fb3cd0.jpeg
图片
thenCombine组合结果:

thenCombine方法将两个无关的CompletableFuture组合起来,第二个Completable并不依赖第一个Completable的结果 提供了三个方法:

//方法一
public <U,V> CompletableFuture<V> thenCombine( 
    CompletionStage<? extends U> other,
    BiFunction<? super T,? super U,? extends V> fn) {
    return biApplyStage(null, other, fn);
}
  //方法二
  public <U,V> CompletableFuture<V> thenCombineAsync(
      CompletionStage<? extends U> other,
      BiFunction<? super T,? super U,? extends V> fn) {
      return biApplyStage(asyncPool, other, fn);
  }

  //方法三
  public <U,V> CompletableFuture<V> thenCombineAsync(
      CompletionStage<? extends U> other,
      BiFunction<? super T,? super U,? extends V> fn, Executor executor) {
      return biApplyStage(screenExecutor(executor), other, fn);
  }

说明:

  • CompletionStage<? extends U> other参数 => 新的CompletableFuture的计算结果

  • BiFunction<? super T,? super U,? extends V> fn参数 => 定义了两个CompletableFuture对象完成计算后 如何合并结果,该参数是一个函数式接口,因此可以使用Lambda表达式

  • Executor executor参数 => 自定义线程池

  • 同理以async结尾的方法将会在一个新的线程中执行组合操作

示例:

public class ThenCombineTest {
    private static Random random = new Random();
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> result = CompletableFuture.supplyAsync(ThenCombineTest::randomInteger).thenCombine(
                CompletableFuture.supplyAsync(ThenCombineTest::randomInteger), (i, j) -> i * j
        );

        System.out.println(result.get());
    }

    public static Integer randomInteger() {
        return random.nextInt(100);
    }
}

将两个线程计算出来的值做一个乘法在返回 执行流程图:

937c3192dff9faee4eaf56ff72b215ce.jpeg
图片
allOf&anyOf组合多个CompletableFuture:

方法介绍:

//allOf
public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs) {
    return andTree(cfs, 0, cfs.length - 1);
}
//anyOf
public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs) {
    return orTree(cfs, 0, cfs.length - 1);
}

说明:

  • allOf => 所有的CompletableFuture都执行完后执行计算。

  • anyOf => 任意一个CompletableFuture执行完后就会执行计算

示例:

  • allOf方法测试

public class AllOfTest {
  public static void main(String[] args) throws ExecutionException, InterruptedException {
      CompletableFuture<Void> future1 = CompletableFuture.supplyAsync(() -> {
          System.out.println("hello");
          return null;
      });
      CompletableFuture<Void> future2 = CompletableFuture.supplyAsync(() -> {
          System.out.println("world"); return null;
      });
      CompletableFuture<Void> result = CompletableFuture.allOf(future1, future2);
      System.out.println(result.get());
  }
}

allOf方法没有返回值,适合没有返回值并且需要前面所有任务执行完毕才能执行后续任务的应用场景

  • anyOf方法测试

public class AnyOfTest {
  private static Random random = new Random();
  public static void main(String[] args) throws ExecutionException, InterruptedException {
      CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
          randomSleep();
          System.out.println("hello");
          return "hello";});
      CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
          randomSleep();
          System.out.println("world");
          return "world";
      });
      CompletableFuture<Object> result = CompletableFuture.anyOf(future1, future2);
      System.out.println(result.get());
 }
  
  private static void randomSleep() {
      try {
          Thread.sleep(random.nextInt(10));
      } catch (InterruptedException e) {
          e.printStackTrace();
      }
  }
}

两个线程都会将结果打印出来,但是get方法只会返回最先完成任务的结果。该方法比较适合只要有一个返回值就可以继续执行其他任务的应用场景

注意点

很多方法都提供了异步实现【带async后缀】,但是需小心谨慎使用这些异步方法,因为异步意味着存在上下文切换,可能性能不一定比同步好。如果需要使用异步的方法,先做测试 ,用测试数据说话!!!

CompletableFuture的应用场景

存在IO密集型的任务可以选择CompletableFuture,IO部分交由另外一个线程去执行。Logback、Log4j2异步日志记录的实现原理就是新起了一个线程去执行IO操作,这部分可以以CompletableFuture.runAsync(()->{ioOperation();})的方式去调用。如果是CPU密集型就不推荐使用了推荐使用并行流

优化空间

supplyAsync执行任务底层实现:

public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
    return asyncSupplyStage(asyncPool, supplier);
}
static <U> CompletableFuture<U> asyncSupplyStage(Executor e, Supplier<U> f) {
    if (f == null) throw new NullPointerException();
    CompletableFuture<U> d = new CompletableFuture<U>();
    e.execute(new AsyncSupply<U>(d, f));
    return d;
}

底层调用的是线程池去执行任务,而CompletableFuture中默认线程池为ForkJoinPool

private static final Executor asyncPool = useCommonPool ?
        ForkJoinPool.commonPool() : new ThreadPerTaskExecutor();

ForkJoinPool线程池的大小取决于CPU的核数。CPU密集型任务线程池大小配置为CPU核心数就可以了,但是IO密集型,线程池的大小由CPU数量 * CPU利用率 * (1 + 线程等待时间/线程CPU时间) 确定。而CompletableFuture的应用场景就是IO密集型任务,因此默认的ForkJoinPool一般无法达到最佳性能,我们需自己根据业务创建线程池


欢迎加入我的知识星球,全面提升技术能力。

👉 加入方式,“长按”或“扫描”下方二维码噢:

de8825a3338bff9aa963a3c13c5c7d62.png

星球的内容包括:项目实战、面试招聘、源码解析、学习路线。

66e1a60969d4cb6b36437a7be78ef8f3.png

dfc9220cddc7cd9bbac6f7545981e8aa.pngddca27d2a080ec962f84b00dde1076b3.png26bad7aeedc5fde1819427a4e7f06785.pngae05fd0aad6a51b44880cce5cec79631.png

文章有帮助的话,在看,转发吧。
谢谢支持哟 (*^__^*)
Simulink实战:5步搞定固定翼飞行器六自由度动力学建模(附模型下载) 本文提供了一份详细的Simulink实战指南,通过5个核心步骤手把手教你构建固定翼飞行器的六自由度动力学模型。内容涵盖从顶层架构设计、核心方程手动实现,到模型集成、测试调试及进阶优化的完整流程,旨在帮助航空航天学生和工程师将抽象理论转化为可运行的仿真模型,并附有模型下载。 阅读详情

相关推荐

避坑指南:WSL2网络模式修改导致无法上网的解决方案(附备份还原技巧)

本文深入解析WSL2默认网络隔离机制,并提供三种安全的端口互通方案,重点推荐通过配置Windows防火墙规则实现稳定访问。同时,针对网络配置修改可能引发的无法上网问题,给出了从重置配置到系统级备份的完整恢复指南,确保开发环境安全可靠。

jj890的博客 785

【译】CompletableFuture 是否非阻塞

高性能和高可用性是现代软件开发的基本要素之一。通过非阻塞和异步编程可以实现这一目标。在 Java 中,_CompletableFuture _类提供了一种编写非阻塞代码的方法。但它真的是非阻塞的吗?在本教程中,我们将检查_ CompletableFuture _在哪些情况下是阻塞的以及在哪些情况下是非阻塞的。首先,让我们简要介绍一下类。它是Java 8中作为并发API的一部分引入的一个强大的类。此外,它实现了Future接口,并代表_ _接口的主要实现。

悟鸣的技术博客 1403

从零到一:移远EC200UCN_LA OpenCPU开发中的‘避坑’实战指南

本文详细介绍了移远EC200UCN_LA 4G通信模块的OpenCPU开发实战指南,涵盖开发环境搭建、项目构建、通信接口开发、调试技巧及固件升级等关键环节。通过避坑经验和实用技巧,帮助开发者高效完成二次开发,提升4G通信模块的应用开发效率。

weixin_29159711的博客 508

解决CompletableFuture异常阻塞

工作中遇到了关于CompletableFuture的一个坑,在此和大家分享一下避免踩坑 先说一下场景,为什么使用异步处理: 博主的项目有一块功能是暴露RPC接口,调用方调用后需要立即返回,同时接口被调用后需要去做其他任务。 一开始是同步进行,先做任务再返回值给调用方,这在生产环境上就出了问题: 数据太多导致同步调用耗时总共9分钟,导致调用方一直等待我方服务返回,无法进行后续操作 为了解决同步调用问题,因此引入了CompletableFuture异步执行任务,关于CompletableFuture的用法这

weixin_42742643的博客 9945

Cadence Allegro实战:如何精准导入结构DXF文件避免安装偏差(附图层配置技巧)

本文详细讲解了在Cadence Allegro中精准导入结构DXF文件以避免安装偏差的实战技巧。核心在于导入前的单位校准、创建专用图层结构,以及基于坐标基准点的精确对齐方法。文章还分享了将DXF图形转化为正式板框和禁布区、高效管理图层以及向结构工程师导出DXF的完整流程,帮助PCB工程师确保设计与机械结构完美契合。

1a2s3d4f5g的博客 510

LabVIEW与三菱PLC通讯实战:ActiveX控件在FX5U上的应用技巧

本文深入探讨了如何利用三菱MX Component中的ActiveX控件,在LabVIEW中实现与FX5U系列PLC的高效、稳定通讯。文章从环境配置、ActiveX控件生命周期管理、数据读写性能优化及容错机制等实战角度,分享了构建工业级健壮通讯程序的核心技巧与架构设计思路。

qsc9012345的博客 891

Java IO | 异步编程 | 使用CompletableFuture进行非阻塞IO

CompletableFuture是Java中的一个类,用于支持异步编程和处理异步任务的结果。它提供了一种方便的方式来处理异步操作,并允许我们以非阻塞的方式执行任务。

devops 4448

黑猫带你学UFS协议第2篇:UFS相关名词释义

本文依据UFSJEDEC3.1、个人工作经验整理而成,如有错误请留言。文章为个人辛苦整理,付费内容,已加入原创保护,禁止私自转载。文章所在专栏《黑猫带你学UFS协议详解》

黑猫奥利奥的博客 5318

java开发:java多线程(五):CompletableFuture实现异步非阻塞获取数据

java创建线程总共有三种方式: 1.继承Thread类 2.实现runnable接口 3.实现Callable接口 他们三者的区别是Callable可以返回结果值,而前俩者无法返回结果值。假若我们的主线程需要子线程去执行异步操作获取数据作为某个函数的输入,我们可以使用Callable方式创建线程。 Callable方式创建线程: //实现Callable接口 public class MyC...

一个程序员-二白的博客 3188

DRM遇到的实际问题及领悟(3)

DRM遇到的实际问题及领悟(3)

phmatthaus的专栏 639

2023华为od机试真题【恢复数字序列】C++

2023华为od机试真题【恢复数字序列】C++ 对于一个连续正整数组成的序列,可以将其拼接成一个字符串,再将字符串里的部分字符打乱顺序。如序列8 9 10 11 12,拼接成的字符串为89101112,打乱一部分字符后得到90811211,原来的正整数10就被拆成了0和1。现给定一个按如上规则得到的打乱字符的字符串,请将其还原成连续正整数序列,并输出序列中最小的数字. 输入描述

MISAYAONE的博客 5732

CompletableFuture让你的代码免受阻塞之苦

前言 现在大部分的CPU都是多核,我们都知道想要提升我们应用程序的运行效率,就必须得充分利用多核CPU的计算能力;Java早已经为我们提供了多线程的API,但是实现方式略微麻烦,今天我们就来看看Java8在这方面提供的改善。 假设场景 现在你需要为在线教育平台提供一个查询用户详情的API,该接口需要返回用户的基本信息,标签信息,这两个信息存放在不同位置,需要远程调用来获取这两个信息;为了模拟远程调用,我们需要在代码里面延迟 1s; public interface RemoteLoader {

Silently9527’s Blog 5064

如何通过 GitHub Actions 使用 SSH 自动化部署到阿里云 ECS 实例

通过 GitHub Actions 和 SSH 自动化部署,可以显著提高你的开发效率和部署的可靠性。本文介绍了如何生成 SSH 密钥、将公钥添加到阿里云 ECS 实例、将私钥添加到 GitHub Secrets,以及编写 GitHub Actions 工作流来实现自动化部署。希望这篇文章对你有所帮助!

吃面不喝汤的博客 1514

CompletableFuture:让你的代码免受阻塞之苦

文章目录前言场景说明CompletableFuture使用CompletableFuture的创建:结果的获取:异常处理:同步方法Pick异步方法查询所有店铺某个商品价格为什么仍需要CompletableFuture其他API介绍whenComplete计算结果的处理提供了三个方法说明示例thenApply转换提供了三个方法说明示例thenAccept结果处理提供了三个方法说明示例thenCompose异步结果流水化提供了三个方法说明示例执行流程图thenCombine组合结果提供了三个方法说明示例执行..

yangxiaofei_java的博客 1960

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

异步神器CompletableFuture:让你的代码免受阻塞之苦

通过阅读本篇文章你将了解到: CompletableFuture的使用 CompletableFure异步和同步的性能测试 已经有了Future为什么仍需要在JDK1.8中引入CompletableFuture CompletableFuture的应用场景 对CompletableFuture的使用优化 场景说明 查询所有商店某个商品的价格并返回,并且查询商店某个商品的价格的API为同步 一个Shop类,提供一个名为getPrice的同步方法 店铺类:Shop.java public cl

LoveSummer 3233

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

代替 Future 的 CompletableFuture让你的代码免受阻塞之苦

IT牧场2022-01-11 21:20 点击下方“IT牧场”,选择“设为星标” IT牧场 IT牧场公众号,BAT 技术专家分享开发、架构、运维相关干货! 159篇原创内容 公众号 作者 |何甜甜在吗 来源 |https://juejin.cn/post/6844904024332828685 通过阅读本篇文章你将了解到: CompletableFuture的使用 CompletableFure异步和同步的性能测试 已经有了Future为什么仍需要在J...

竹林幽深 604

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

【199期】CompletableFuture:让你的代码免受阻塞之苦​

点击上方“Java精选”,选择“设为星标”别问别人为什么,多问自己凭什么!下方有惊喜,留言必回,有问必答!每天08:15更新文章,每天进步一点点...写在前面通过阅读本篇文章你将了解到...

Java精选 346
上一篇: 医生都是越老越吃香,为啥程序员却不是?
下一篇: Feign 如何设置超时时间,不同情况下还真不一样
公众号-芋道源码
博客等级 码龄10年 1639粉丝 377原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值