Thread pool and CompletableFuture asynchronous orchestration

The benefits of using the thread pool:
1. Reduce resource consumption.
Reduce the loss caused by thread creation and destruction by reusing the created threads.
2. Improve response speed
because the number of threads in the thread pool does not exceed the maximum limit of the thread pool. , some threads are in the state of waiting for assigned tasks ,
and when the tasks come, they can be executed without creating new threads System overhead caused by threads . Unlimited creation and destruction of threads not only consumes system resources, but also reduces the stability of the system, using the thread pool for uniform allocation



The following code first creates a thread pool executorand passes it to the asynchronous orchestration object CompletableFuture, which provides four static methods to create an asynchronous operation.

1. Create an asynchronous object method

insert image description here

1、runXxxx 都是没有返回结果的,supplyXxx 都是可以获取返回结果的
2、可以传入自定义的线程池,否则就用默认的线程池
public class Thread1Test {
    
    

    public static ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
    
    
        System.out.println("方法开始。。。");

        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
    
    
            System.out.println("当前线程" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println(i);
        }, executor);
        System.out.println("方法结束");

    }
}

insert image description here

2. The callback method when the calculation is completed

supplyAsyncYou can get the thread running return result by using :

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    
    
            System.out.println("当前线程" + Thread.currentThread().getId());
            int i = 10 / 2;
            System.out.println("运行结果"+i);
            return i;
        }, executor);
        Integer integer = future.get();

Provides a callback method when the calculation is completed , and operates on the result after the processing is completed:
insert image description here
whenComplete can handle normal and abnormal calculation results, and exceptionally handles abnormal conditions.
The difference between whenComplete and whenCompleteAsync:
whenComplete: the thread that executes the current task executes the task that continues to execute whenComplete.
whenCompleteAsync: It is to continue to submit the task of whenCompleteAsync to the thread pool
for execution.
The method does not end with Async, which means that Action uses the same thread to execute, and Async may use other threads
to execute (if it uses the same thread pool, it may also be selected by the same thread to execute)
whenCompleteto get the task completion result, parameter 1 is the result, parameter 2 is the exception:

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    
    
            System.out.println("当前线程" + Thread.currentThread().getId());
            int i = 10 / 0;
            System.out.println("运行结果"+i);
            return i;
        }, executor).whenComplete((res,excption)->{
    
    
            System.out.println("异步完成,结果是"+res+"异常是:"+excption);
        });

An exception with a divisor of 0 is created here:
insert image description here
exceptionallyalthough the exception information can be obtained, the returned data cannot be modified, the exception is sensed, and the default value is returned

 CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    
    
            System.out.println("当前线程" + Thread.currentThread().getId());
            int i = 10 / 0;
            System.out.println("运行结果"+i);
            return i;
        }, executor).whenComplete((res,excption)->{
    
    
            System.out.println("异步完成,结果是"+res+"异常是:"+excption);
        }).exceptionally(throwable -> {
    
    
            //感知异常,返回默认值
            return 10;
        });
        Integer integer = future.get();

insert image description here

3. handle method

insert image description here
handle is the same as complete, it can do final processing on the result (can handle exceptions), and can change the return value.

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
    
    
            System.out.println("当前线程" + Thread.currentThread().getId());
            int i = 10 / 4;
            System.out.println(i);
            return i;
        }, executor).handle((res,thr)->{
    
    
            if (res!=null){
    
    
                return res *2;
            }
            if (thr!=null){
    
    
                return 0;
            }
            return 1;
        });

insert image description here

4. Thread serialization method

insert image description here
thenApplyMethod: When a thread depends on another thread, get the result returned by the previous task and return the
return value of the current task.
thenAcceptMethod: Consume the processing result. Receive the processing result of the task, and consume the processing, and return no result.
thenRunMethod: As long as the above task is executed, thenRun will be executed. After the task is processed, the
follow-up operation of thenRun will be executed
. With Async, an additional thread is opened, which is executed asynchronously. Same as before.
All of the preceding tasks must be successfully completed.

      //线程串行化
        /* 1、 thenRunAsync 不能获取上一步的执行结果
           2、 thenAcceptAsync 能接受上一步结果,但无返回值
           3、 thenApplyAsync能接受上一步结果,有返回值
        * */
 CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    
    
            System.out.println("当前线程" + Thread.currentThread().getId());
            int i = 10 / 4;
            System.out.println("运行结果"+i);
            return i;
        }, executor).thenApplyAsync(res -> {
    
    
            System.out.println("任务2启动了" + res);

            return "hello" + res;
        }, executor);

insert image description here

5. Combination of two tasks - both must be completed

insert image description here
Both tasks must be completed to trigger this task.

runAfterBoth: Combining two futures, you don't need to get the results of the futures, you only need to process the task after the two futures have finished
processing the task.

CompletableFuture<Integer> future01 = CompletableFuture.supplyAsync(() -> {
    
    
            System.out.println("任务1线程" + Thread.currentThread().getId());
            int i = 10 / 4;
            System.out.println("任务1线程结束"+i);
            return i;
        }, executor);

        CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {
    
    
            System.out.println("任务2线程" + Thread.currentThread().getId());

            System.out.println("任务2线程结束");
            return "hello";
        }, executor);
        future01.runAfterBothAsync(future02,()->{
    
    
            System.out.println("任务3开始");
        },executor);

        System.out.println("方法结束");

insert image description here
thenAcceptBoth: Combine two futures, get the return results of the two future tasks, and then process the tasks without
return value.

future01.thenAcceptBothAsync(future02,(f1,f2)->{
    
    
           System.out.println("任务3开始...之前的结果"+f1+f2);
       },executor);

insert image description here

thenCombine: Combine two futures, get the return results of the two futures, and return the return value of the current task

 CompletableFuture<String> future = future01.thenCombineAsync(future02, (f1, f2) -> {
    
    
            return "组合处理任务1、2的结果" + f1 + f2 + "999";
        }, executor);

insert image description here

6. Combination of two tasks - one completed

insert image description here

runAfterEither: One of the two tasks is completed, there is no need to get the result of the future, process the task, and there is no return
value.

 future01.runAfterEitherAsync(future02,()->{
    
    
           System.out.println("任务3开始前的结果");
       },executor);

insert image description here
acceptEither: One of the two tasks is completed, get its return value, process the task, and there is no new return value.

future01.acceptEitherAsync(future02,(res)->{
    
    
            System.out.println("任务3开始前的结果"+res);
        },executor);

insert image description here
applyToEither: One of the two tasks is completed, get its return value, process the task and have a new return value.

CompletableFuture<String> eitherAsync = future01.applyToEitherAsync(future02, (res) -> {
    
    
            System.out.println("任务3开始前结果" + res);
            return res.toString() + "--->" + "ke";
        }, executor);

        System.out.println("方法结束"+eitherAsync.get());

insert image description here

7. Multitasking combination

insert image description here

allOf: wait for all tasks to complete

  CompletableFuture<String> img = CompletableFuture.supplyAsync(() -> {
    
    
            System.out.println("查询商品信息");
            return "hello.jpg";
        },executor);
        CompletableFuture<String> attr = CompletableFuture.supplyAsync(() -> {
    
    
            System.out.println("查询属性信息");
            return "黑丝";
        },executor);
        CompletableFuture<String> desc = CompletableFuture.supplyAsync(() -> {
    
    
            try {
    
    
                Thread.sleep(3000);
                System.out.println("查询商品介绍");

            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
            return "油量";
        },executor);
        CompletableFuture<Void> allOf = CompletableFuture.allOf(img, attr, desc);
        allOf.get();
        System.out.println("任务结束"+img.get()+attr.get()+desc.get());

insert image description here
anyOf: As long as there is one task completed

 CompletableFuture<Object> anyOf = CompletableFuture.anyOf(img, attr, desc);

insert image description here

Guess you like

Origin blog.csdn.net/weixin_42260782/article/details/131258160