【Java难点】多线程-进阶

Start开启线程源码分析

  1. Thread.start开启线程
public class JUC01 {
    public static void main(String[] args) {
        Thread t1 = new Thread(
                () -> System.out.println("开启线程:"+Thread.currentThread().getName()),
                "t1");
        t1.start();
    }
}
  1. start方法源码
    public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this);

        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }
  1. start方法中调用start0方法,start0方法是native方法,底层使用c++编写
private native void start0();

总结:

java线程是通过start的方法启动执行的,主要内容在native方法start0中,openjdk的写JNI一般是一一对应的,Thread.java对应的就是Thread.c,start0其实就是JVM_StartThread。此时查看源代码可以看到在jvm.h中找到了声明,jvm.cpp中有实现。

jvm配合操作系统,底层由操作系统分配了一个原生的基础线程。

image-20240421220958017

Future接口

Future是Java5新加的一个接口,它提供了一种异步并行计算的功能。如果主线程需要执行一个很耗时的计算任务,我们就可以通过Future把这个任务放到异步线程中执行。主线程继续处理其他任务或者先行结束,再通过Future获取计算结果。

FutureTask类

FutureTask实现了RunnableFuture接口,RunnableFuture接口实现了Runnable接口和Future接口,FutureTask有一个构造方法:FutureTask(Callable callable)

实现Runnable接口后,可以使用new Thread(Runnable r)开启多线程;

Future接口中有可以取消已启动的线程的方法;

FutureTask的构造方法FutureTask(Callable callable)使用构造注入的方式将Callable为自身所用,可以使用Callable接口的call方法编写多线程的逻辑,且call方法有返回值。

实例:

image-20240421233616447

FutureTask的缺点:

  1. get方法容易阻塞

image-20240422214310869

一般建议将get方法放在程序后面,假如不愿意等待很长时间,可以使用get(long timeout, TimeUnit unit)设置超时自动离开。

image-20240422215338251

  1. isDone轮询会耗费无谓的cpu资源,而且也不见得能及时地得到计算结果。

image-20240422220045893

结论:Future对于结果的获取不是很友好,只能通过阻塞或轮询的方式得到任务的结果。

CompletableFuture类

get方法阻塞的方式和异步编程的设计理念相违背,而轮询的方式会耗费无谓的CPU资源。因此,
JDK8设计出CompletableFuture。

CompletableFuture提供了一种观察者模式类似的机制,可以让任务执行完成后通知监听的一方。

在Java8中,CompletableFuture提供了非常强大的Future的扩展功能,可以帮助我们简化异步编程的复杂性,并且提供了函数式编程的能力,可以通过回调的方式处理计算结果,也提供了转换和组合 CompletableFuture的方法。它可能代表一个明确完成的Future,也有可能代表一个完成阶段(CompletionStage),它支持在计算完成以后触发一些函数或执行某些动作。

public class CompletableFuture<T> implements Future<T>, CompletionStage<T> {}

CompletionStage接口:

CompletionStage代表异步计算过程中的某一个阶段,一个阶段完成以后可能会触发另外一个阶段,有些类似Linux系统的管道分隔符传参数:

  • CompletionStage代表异步计算过程中的某一个阶段,一个阶段完成以后可能会触发另外一个阶段
  • 一个阶段的计算执行可以是一个Function,Consumer或Runnable。 比如:stage.thenApply(x -> square(x)).thenAccept(x -> System.out.print(x)).thenRun(() -> System.out.printin())
  • 一个阶段的执行可能是被单个阶段的完成触发,也可能是由多个阶段一起触发
四个静态方法

尽量不要使用构造方法获得CompletableFuture对象,尽量使用四个静态方法获取。

  1. 返回值为Void
public static CompletableFuture<Void> runAsync(Runnable runnable)
public static CompletableFuture<Void> runAsync(Runnable runnable,Executor executor)
  1. 返回值为泛型U
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,Executor executor)

参数:

  • Executor:

没有传入指定的Executor,直接使用默认的ForkJoinPool.commonPool()作为它的线程池执行异步代码

如果指定线程池,则使用我们自定义的或者特别指定的线程池执行异步代码

  • Runnable:

传入Runnable的两个方法均无返回值

  • Supplier

供给型函数接口

image-20240422225448328

实例:

runAsync方法不传入线程池

image-20240422225043408

runAsync方法传入线程池

image-20240422225207834

supplyAsync方法不传入线程池

image-20240422225602925

image-20240422225634081

CompletableFuture的使用

从Java8开始引入了CompletableFuture,它是Future的功能增强版,减少阻塞和轮询,可以传入回调对象,当异步务完成或者发生异常时,自动调用回调对象的回调方法。

实例:

import java.util.concurrent.*;

public class JUC01 {
    public static void main(String[] args) {
        //创建线程池
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        try {
            CompletableFuture.supplyAsync(() -> {
                System.out.println(Thread.currentThread().getName() + "------come in");
                int result = ThreadLocalRandom.current().nextInt(10);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("------1秒钟后出结果" + result);
                return result;
            }, threadPool)
            //当上一步(supplyAsync)运行结束时执行whenComplete分支,v表示上一步返回的结果,e表示上一步出现的异常
            //注意:无论上一步(supplyAsync)是否出现异常,都会执行whenComplete分支
            .whenComplete((v, e) -> {
                if (e == null) { //上一步不出现异常时执行
                    System.out.println("------计算完成,更新系统UpdateValue:" + v);
                }
            })
            //当上一步(supplyAsync)出现异常时执行exceptionally分支,e表示上一步出现的异常
            .exceptionally(e -> {
                e.printStackTrace();
                System.out.println("异常情况:" + e.getCause() + "\t" + e.getMessage());
                return null;
            });
            System.out.println(Thread.currentThread().getName()+"线程先去往其他任务");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
          	//关闭线程池
            threadPool.shutdown();
        }
    }
}

image-20240422234251424

注意:使用默认的线程池时,会把CompletableFuture.supplyAsync产生的线程设置为守护线程,当main线程结束时,守护线程也会随之结束。

优点

image-20240422234530765

get和join

get方法和join方法都能获得线程的返回值,区别是get会抛出受检异常,join会抛出非受检异常(运行时异常)。

get方法

image-20240425011040021

join方法

image-20240425011010780

函数式接口与链式调用

函数式接口

Runnable

无参数、无返回值

image-20240425005118223

Function

功能型函数式接口,有1个参数,有返回值

image-20240425005228048

Consumer

消费型函数式接口,有1参数,无返回值

image-20240425005331068

BiConsumer

BiConsumer<T, U> 接受2个参数(Bi,英文单词词根,代表两个的意思),没有返回值

image-20240425005527971

Supplier

供给型函数式接口,没有参数,有返回值

image-20240425005814758

总结

image-20240425010002772

链式调用 image-20240425010447943
电商比价

案例说明:电商比价需求,模拟如下情况:

  1. 需求:
    1.1 同一款产品,同时搜索出同款产品在多大电商平台的售价;
    1.2 同一款产品,同时搜索出本产品在同一个电商平台下,各个入驻卖家售价是多少
  2. 输出:

​ 出来结果希望是同款产品的在不同地方的价格清单列表,返回一个List<String>
​ 《mysql》 in jd price is 88.05
​ 《mysql》in dangdang price is 86.11
​ 《mysql》 in taobao price is 90.43

  1. 技术要求
    3.1 函数式编程
    3.2 链式編程
    3.3 stream流式计算

测试1:单线程执行

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class JUC03 {
    /**
     * 电商列表
     */
    static List<NetMall> list= Arrays.asList(
            new NetMall("jd"),
            new NetMall("taobao"),
            new NetMall("dangdang")
    );
    public static List<String> getPrice(List<NetMall> list,String productName){
        return list
                .stream()
                .map(
                    netMall -> String.format(productName + " in %s price is %.2f",
                    netMall.getName(),
                    netMall.calcPrice(productName)))
                .collect(Collectors.toList());
    }
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        getPrice(list, "mysql").forEach(System.out::println);
        long endTime = System.currentTimeMillis();
        System.out.println("--------costTime:"+(endTime-startTime)+"毫秒");
    }
}

/**
 * 电商类
 */
@Data
@AllArgsConstructor
class NetMall{
    /**
     * 电商名称
     */
    private String name;

    /**
     * 模拟查询商品的价格
     */
    public double calcPrice(String productName){
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return ThreadLocalRandom.current()
                .nextDouble()*2+productName.charAt(0);
    }
}

image-20240425205845618

测试2:并行流:stream().parallel(),缺点:并行流不能设置线程池

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class JUC03 {
    /**
     * 电商列表
     */
    static List<NetMall> list= Arrays.asList(
            new NetMall("jd"),
            new NetMall("taobao"),
            new NetMall("dangdang")
    );
    public static List<String> getPrice(List<NetMall> list,String productName){
        return list
                .stream()
                .parallel()
                .map(
                    netMall -> String.format(productName + " in %s price is %.2f",
                    netMall.getName(),
                    netMall.calcPrice(productName)))
                .collect(Collectors.toList());
    }
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        getPrice(list, "mysql").forEach(System.out::println);
        long endTime = System.currentTimeMillis();
        System.out.println("--------costTime:"+(endTime-startTime)+"毫秒");
    }
}

/**
 * 电商类
 */
@Data
@AllArgsConstructor
class NetMall{
    /**
     * 电商名称
     */
    private String name;

    /**
     * 模拟查询商品的价格
     */
    public double calcPrice(String productName){
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return ThreadLocalRandom.current()
                .nextDouble()*2+productName.charAt(0);
    }
}

image-20240425205808105

测试3:异步多任务

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class JUC03 {
    /**
     * 电商列表
     */
    static List<NetMall> list= Arrays.asList(
            new NetMall("jd"),
            new NetMall("taobao"),
            new NetMall("dangdang")
    );
    public static List<String> getPrice(List<NetMall> list,String productName){
        return list.stream().map(netMall ->
                CompletableFuture.supplyAsync(() ->
                String.format(productName + "in %s price is %.2f",
                netMall.getName(),
                netMall.calcPrice(productName))))
                .collect(Collectors.toList())
                .stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());
    }
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        getPrice(list, "mysql").forEach(System.out::println);
        long endTime = System.currentTimeMillis();
        System.out.println("--------costTime:"+(endTime-startTime)+"毫秒");
    }
}

/**
 * 电商类
 */
@Data
@AllArgsConstructor
class NetMall{
    /**
     * 电商名称
     */
    private String name;

    /**
     * 模拟查询商品的价格
     */
    public double calcPrice(String productName){
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return ThreadLocalRandom.current()
                .nextDouble()*2+productName.charAt(0);
    }
}

image-20240425205647566

image-20240425205731467

CompletableFuture常用方法

获取结果和触发计算的方法

获取结果:

  1. public T get() throws InterruptedException, ExecutionException

​ 等待返回结果,会发生阻塞(不见不散)

  1. public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException

​ 设置超时时间,超过时间还没有返回结果则抛出异常(过时不候)

  1. public T join()

​ 和get()效果相同,不会抛出受检异常

  1. public T getNow(T valueIfAbsent)

​ 立即获取结果不阻塞,如果没计算完,则返回设定的valueIfAbsent值,如果计算完成,则返回完成后的结果

主动触发计算:

  1. public boolean complete(T value)

​ 是否打断了get/join方法,如果打断了,则将value返回给get/join方法,并返回true;如果没打断,

则不会将value返回给get/join方法,并返回false;

  • 打断get/join方法:
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class JUC03 {
    public static void main(String[] args) {
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "abc";
        });
        System.out.println(completableFuture.complete("计算未完成,将自定义的值返回给你吧"));
        System.out.println(completableFuture.join());
    }
}

image-20240425213059151

  • 未打断get/join方法
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class JUC03 {
    public static void main(String[] args) {
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "abc";
        });
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(completableFuture.complete("计算未完成,将自定义的值返回给你吧"));
        System.out.println(completableFuture.join());
    }
}

image-20240425213200602

**注意:**get/join方法放在complete之后,get/join方法永远不会阻塞,因为异步任务如果没计算完,complete方法会将value给get/join方法,get/join方法获取的是value,不会发生阻塞;异步任务如果已经计算完成,则会将计算结果返回给get/join方法,更不会阻塞。

对计算结果进行处理的方法
  1. public <U> CompletableFuture<U> thenApply( Function<? super T,? extends U> fn)

​ 计算结果存在依赖关系,这两个线程串行化。

**实例:**买鱼,杀鱼,腌鱼存在依赖关系,需要串行处理,而腌鱼的过程中可以去打游戏,所以打游戏和腌鱼是并行处理。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class JUC03 {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        try {
            CompletableFuture.supplyAsync(() -> {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("第一步、买鱼");
                return 1;
            }, threadPool).thenApply(f -> {
                System.out.println("第二步、杀鱼");
                return f + 2;
            }).thenApply(f -> {
                System.out.println("第三步、腌鱼");
                return f + 3;
            }).whenComplete((v, e) -> {
                if (e == null) {
                    System.out.println("-----正在腌鱼:" + v);
                }
            }).exceptionally(e -> {
                e.printStackTrace();
                System.out.println(e.getMessage());
                return null;
            });
            System.out.println(Thread.currentThread().getName() + "----腌鱼的过程中可以先去打游戏");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }
    }
}

image-20240425222129186

**异常处理:**由于存在依赖关系(当前步错,不走下一步),当前步骤有异常的话就叫停。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class JUC03 {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        try {
            CompletableFuture.supplyAsync(() -> {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("第一步、买鱼");
                return 1;
            }, threadPool).thenApply(f -> {
              //出现异常
                int i=1/0;
                System.out.println("第二步、杀鱼");
                return f + 2;
            }).thenApply(f -> {
                System.out.println("第三步、腌鱼");
                return f + 3;
            }).whenComplete((v, e) -> {
                if (e == null) {
                    System.out.println("-----正在腌鱼:" + v);
                }
            }).exceptionally(e -> {
                e.printStackTrace();
                System.out.println(e.getMessage());
                return null;
            });
            System.out.println(Thread.currentThread().getName() + "----腌鱼的过程中可以先去打游戏");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }
    }
}

image-20240425222505611

  1. public <U> CompletableFuture<U> handle( BiFunction<? super T, Throwable, ? extends U> fn)

效果和thenApply方法相同,但是有异常也可以往下一步走,根据带的异常参数可以进一步处理

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class JUC03 {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        try {
            CompletableFuture.supplyAsync(() -> {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("第一步、买鱼");
                return 1;
            }, threadPool).handle((f,e) -> {
                System.out.println("第二步、杀鱼");
                return f + 2;
            }).handle((f,e) -> {
                System.out.println("第三步、腌鱼");
                return f + 3;
            }).whenComplete((v, e) -> {
                if (e == null) {
                    System.out.println("-----正在腌鱼:" + v);
                }
            }).exceptionally(e -> {
                e.printStackTrace();
                System.out.println(e.getMessage());
                return null;
            });
            System.out.println(Thread.currentThread().getName() + "----腌鱼的过程中可以先去打游戏");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }
    }
}

异常处理:

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class JUC03 {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        try {
            CompletableFuture.supplyAsync(() -> {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("第一步、买鱼");
                return 1;
            }, threadPool).handle((f,e) -> {
              //出现异常
                int i=1/0;
                System.out.println("第二步、杀鱼");
                return f + 2;
            }).handle((f,e) -> {
                System.out.println("第三步、腌鱼");
                return f + 3;
            }).whenComplete((v, e) -> {
                if (e == null) {
                    System.out.println("-----正在腌鱼:" + v);
                }
            }).exceptionally(e -> {
                e.printStackTrace();
                System.out.println(e.getMessage());
                return null;
            });
            System.out.println(Thread.currentThread().getName() + "----腌鱼的过程中可以先去打游戏");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }
    }
}

image-20240425223345471

第二步19行位置出现异常,所以不会执行System.out.println("第二步、杀鱼");return f + 2;,所以在第三步return f + 3;位置会出现空指针异常。

对计算结果进行消费方法
  1. public CompletableFuture<Void> thenAccept(Consumer<? super T> action)

​ 接收任务的处理结果,并消费处理,无返回结果。

​ 任务A 执行完执行 B,B需要A的结果,但是任务B无返回值

import java.util.concurrent.CompletableFuture;

public class JUC03 {
    public static void main(String[] args) {
            CompletableFuture.supplyAsync(() -> {
                System.out.println("第一步、买鱼");
                return 1;
            }).handle((f,e) -> {
                System.out.println("第二步、杀鱼");
                return f + 2;
            }).handle((f,e) -> {
                System.out.println("第三步、腌鱼");
                return f + 3;
            }).thenAccept(integer -> System.out.println(integer));
    }
}

image-20240425230735592

**总结:**thenRun、thenAccept、thenApply对比

image-20240425231054832

代码演示:

image-20240425231553933

image-20240425231603865

xxx方法和xxxAsync方法对比

xxx方法有:thenRun、thenAccept、thenApply

image-20240425232623818

对计算速度进行选用的方法

public <U> CompletableFuture<U> applyToEither( CompletionStage<? extends T> other, Function<? super T, U> fn)

两个CompletableFuture对象进行比较,哪个先计算完就对哪个CompletableFuture的返回值使用Function<? super T, U> fn进行处理,然后返回先计算完的CompletableFuture对象。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class JUC03 {
    public static void main(String[] args) {
        CompletableFuture<String> playA = CompletableFuture.supplyAsync(() -> {
            System.out.println("A come in");
            try {
                TimeUnit.MILLISECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "playA";
        });
        CompletableFuture<String> playB = CompletableFuture.supplyAsync(() -> {
            System.out.println("B come in");
            try {
                TimeUnit.MILLISECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "playB";
        });
        CompletableFuture<String> result = playA.applyToEither(playB, f -> {
            return f + " is winner";
        });
        System.out.println(Thread.currentThread().getName()+"\t--------:"+result.join());
    }
}

image-20240425235230513

对计算结果进行合并的方法

public <U,V> CompletableFuture<V> thenCombine( CompletionStage<? extends U> other, BiFunction<? super T,? super U,? extends V> fn)

两个CompletionStage任务都完成后,最终能把两个任务的结果一起交给thenCombine来处理,先完成的先等着,等待其它分支任务完成。

  • 实例1
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class JUC03 {
    public static void main(String[] args) {
        CompletableFuture<Integer> playA = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "\t ----启动");
            try {
                TimeUnit.MILLISECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 30;
        });
        CompletableFuture<Integer> playB = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "\t ----启动");
            try {
                TimeUnit.MILLISECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 20;
        });
        CompletableFuture<Integer> completableFuture = playA.thenCombine(playB, (x, y) -> {
            System.out.println("-----开始两个结果合并");
            return x + y;
        });
        System.out.println(completableFuture.join());
    }
}

image-20240426000241164

  • 实例2:链式调用

image-20240426000439712

  • 18
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值