Feature并行执行程序
创始人
2024-05-29 21:23:14

前言

有时候,我们执行一段代码,去从A获取数据,再去从B获取数据,而后从C获取数据,三个业务如果按照串行执行,需要的时间是A+B+C的时间。然而三个业务是可以独立执行的,没有前后约束条件。

代码示例

示例

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;import java.util.concurrent.*;@SpringBootTest
class DemoFeatureApplicationTests {@Testpublic void feature() throws InterruptedException {long s = System.currentTimeMillis();ExecutorService executor = Executors.newCachedThreadPool();final Future futureA = executor.submit(new Callable() {public Double call() {try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}return 1.2;}});final Future futureB = executor.submit(new Callable() {public Double call() {try {Thread.sleep(6000);} catch (InterruptedException e) {e.printStackTrace();}return 1.3;}});final Future futureC = executor.submit(new Callable() {public Double call() {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}return 1.1;}});try {Double result = futureA.get(10, TimeUnit.SECONDS);Double result2 = futureB.get(10, TimeUnit.SECONDS);Double result3 = futureC.get(10, TimeUnit.SECONDS);System.out.println("计算结果:" + (result + result2 + result3));System.out.println("耗时:" + (System.currentTimeMillis() - s));} catch (Exception e) {e.printStackTrace();}}
}

示例代码分别表示A业务5秒,B业务6秒,C业务1秒,如果串行执行则需要12秒。那么使用Feature串行后,执行后可见,其使用时间6006毫秒,显然各业务并行执行。
在这里插入图片描述

Feature有什么用?

  • 利用Feature可以让充分利用处理器的并发执行能力,提高程序的运行效率。
  • Feature 在所有任务都执行完后,一并get结果。

相关内容

热门资讯

重大科普!微信卡五星辅助器,微... 重大科普!微信卡五星辅助器,微乐自建房脚本免费入口(开挂自建房)工具1.微信卡五星辅助器 选牌创建新...
玩家必备科普!微乐自建房辅助工... 玩家必备科普!微乐自建房辅助工具脚本,微乐自建房脚本免费入口(开挂自建房)软件1、任何微乐自建房辅助...
安装程序教程!微信卡五星辅助器... 安装程序教程!微信卡五星辅助器,微乐小程序免费黑科技(开挂自建房)插件1、玩家可以在微信卡五星辅助器...
最新技巧!微乐家乡麻将自建房辅... 最新技巧!微乐家乡麻将自建房辅助app,微乐小程序免费黑科技(开挂自建房)工具最新技巧!微乐家乡麻将...
科技分享!微乐小程序麻将自建房... 科技分享!微乐小程序麻将自建房辅助工具插件,微乐自建房脚本免费入口(开挂自建房)app1、微乐小程序...