并发编程-ComplateFuture的使用

106 阅读1分钟

常用方法

  1. supplyAsync:异步运行任务并带有返回值
  2. runAsync:异步运行任务没有返回值
  3. get:获取返回值
  4. thenApplyAsync:任务执行完毕后异步执行下一个任务并带有返回值
  5. thenRunAsync:任务执行完毕后异步执行下一个任务没有返回值
  6. thenCompose:任务执行完毕后将结果作为参数执行下一个任务
  7. allOf:所有任务完成后返回一个新的任务
  8. anyOf:当任意任务完成后返回一个新的任务
  9. runAfterBothAsync:当两个任务运行结束后异步运行任务

代码实例

  1. 三个任务完成后,执行第四个任务计算前四个任务的合
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class Main {

    public static void main(String[] args) {
        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("Task 1 is running on thread " + Thread.currentThread().getName());
            // 模拟任务执行时间
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Task 1 completed.");
            return 1;
        });

        CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("Task 2 is running on thread " + Thread.currentThread().getName());
            // 模拟任务执行时间
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Task 2 completed.");
            return 2;
        });

        CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(() -> {
            System.out.println("Task 3 is running on thread " + Thread.currentThread().getName());
            // 模拟任务执行时间
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Task 3 completed.");
            return 3;
        });

        CompletableFuture<Void> allTasks = CompletableFuture.allOf(future1, future2, future3);

        CompletableFuture<Integer> combinedFuture = allTasks.thenCompose(v ->
                CompletableFuture.supplyAsync(() -> {
                    int result = 0;
                    try {
                        result = future1.get() + future2.get() + future3.get();
                    } catch (InterruptedException | ExecutionException e) {
                        e.printStackTrace();
                    }
                    return result;
                })
        );

        try {
            System.out.println("Combined result of Task 1, Task 2, and Task 3: " + combinedFuture.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}