java多线程异步并行计算

一、场景

  • 在工作中会碰到,非常耗时的操作,这些操作之间并没有必然的先后顺序,这个时候我们就可以考虑多线程的异步并行计算,来提高性能。
  • 下面我们就直接看代码

二、示例

说明:有三个业务ABC,每个业务耗时5秒,按照一般的写法需要耗时15秒,而如果并行计算,只需要5秒,可以大大提高效率
当然在实际的应用中还要综合考虑 cpu 内存 IO 等多方便的因素,抛砖引玉,这里只给大家提供一个思路。

package future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class FutureTest {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        CompletableFuture<String> futureA = CompletableFuture.supplyAsync(() -> methodA());// 业务A
        CompletableFuture<String> futureB = CompletableFuture.supplyAsync(() -> methodB());// 业务B
        CompletableFuture<String> futureC = CompletableFuture.supplyAsync(() -> methodC());// 业务C

        try {
            System.out.println(futureA.get() + futureB.get() + futureC.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        long end = System.currentTimeMillis();
        System.out.println(end - start);
        System.out.println(methodA() + methodB() + methodC());
        long end2 = System.currentTimeMillis();
        System.out.println(end2 - end);
    }

    private static <U> String methodA(){
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "methodA...";
    }

    private static <U> String methodB() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "methodB...";
    }

    private static <U> String methodC() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "methodC...";
    }
}
打印结果:
methodA...methodB...methodC...
5071
methodA...methodB...methodC...
15002

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×