【CompletableFuture任务编排】

发布时间:2024年01月19日

1.IO线程执行阻塞任务,之后回到逻辑线程

package org.example.testAsync;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class Main {

    private static AtomicInteger ioThreadIndex = new AtomicInteger(0);

    private static ExecutorService logicThread = Executors.newSingleThreadExecutor(r -> {
        Thread t = new Thread(r);
        t.setName("logicThread");
        return t;
    });

    private static ExecutorService executorService = Executors.newFixedThreadPool(10, r -> {
        Thread t = new Thread(r);
        t.setName("ioThread" + ioThreadIndex.getAndIncrement());
        return t;
    });


    public static CompletableFuture<Student> findStudent(String name, int age) {
        return CompletableFuture.supplyAsync(() -> {
            log.info("start find in io thread");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return new Student(name, age);
        }, executorService);  // 在IO线程中运行,传入这个参数
    }

    public static void main(String[] args) {
        logicThread.execute(() -> {
            findStudent("xx", 18)
                    .whenCompleteAsync(((student, throwable) -> {
                        log.info("find name={}", student.getName());
                    }), logicThread); // IO线程中执行完毕后,再次回调到逻辑线程
        });
    }

    /*
    15:00:29.893 [ioThread0] INFO org.example.testAsync.Main -- start find in io thread
    15:00:32.911 [logicThread] INFO org.example.testAsync.Main -- find name=xx
     */

    @Data
    @AllArgsConstructor
    private static class Student {
        private String name;
        private int age;
    }
}

2.任务有依赖关系,并且等待所有任务执行完毕

package org.example.testAsync;

import lombok.extern.slf4j.Slf4j;

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

@Slf4j
public class Main {

    public static void main(String[] args) {
        CompletableFuture<Void> task1 = CompletableFuture.runAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("task1");
        });

        CompletableFuture<Void> task2 = task1.thenRun(() -> {  // 必须是1执行完后执行2
            log.info("task2");
        });

        CompletableFuture<Void> task3 = CompletableFuture.runAsync(() -> {
            log.info("task3");
        });

        // 等待所有的任务执行完毕
        CompletableFuture.allOf(task1, task2, task3).join();

        log.info("all done");
    }
}

/*
15:11:57.012 [ForkJoinPool.commonPool-worker-5] INFO org.example.testAsync.Main -- task3
15:11:58.023 [ForkJoinPool.commonPool-worker-19] INFO org.example.testAsync.Main -- task1
15:11:58.023 [ForkJoinPool.commonPool-worker-19] INFO org.example.testAsync.Main -- task2
15:11:58.023 [main] INFO org.example.testAsync.Main -- all done
 */

文章来源:https://blog.csdn.net/themagickeyjianan/article/details/135698503
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。