有时候,我们执行一段代码,去从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毫秒,显然各业务并行执行。