在某个业务接口中,系统需要调用B、C、D的接口,常规我们可能这样写
@SpringBootTest
public class Thread {
@Test
void demo1() throws InterruptedException {
long startTime = System.currentTimeMillis();
// 调用三个系统
method1();
method2();
method3();
long endTime = System.currentTimeMillis();
System.out.println("执行时间:" + (endTime - startTime) + "毫秒");
}
// 模拟
public static void method1() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(100);
}
public static void method2() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(200);
}
public static void method3() throws InterruptedException {
TimeUnit.MILLISECONDS.sleep(300);
}
}
运行后结果如下
总耗时为BCD三个系统接口请求时间之和。
我们可以通过线程池来进行并行处理,使总耗时变为BCD三个系统中耗时最长的那个,也就是300毫秒,改造如下demo2():
@Test
void demo2(){
// 创建线程池
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 15, 1L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(30));
long startTime = System.currentTimeMillis();
// 使用异步任务
CompletableFuture<Void> customerInfoFuture1 = CompletableFuture.runAsync(() -> {
try {
method1();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}, threadPoolExecutor);
CompletableFuture<Void> customerInfoFuture2 = CompletableFuture.runAsync(() -> {
try {
method2();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}, threadPoolExecutor);
CompletableFuture<Void> customerInfoFuture3 = CompletableFuture.runAsync(() -> {
try {
method3();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}, threadPoolExecutor);
// 等待所有任务完成
CompletableFuture.allOf(customerInfoFuture1, customerInfoFuture2, customerInfoFuture3).join();
long endTime = System.currentTimeMillis();
System.out.println("执行时间:" + (endTime - startTime) + "毫秒");
}
执行结果如下: