Java并行接口开发提高性能:
/**
* 串行
*/
@GetMapping("/user/info")
Result userInfo() throws ExecutionException, InterruptedException {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Thread.sleep(RandomUtil.randomInt(2, 4)*1000);
Thread.sleep(RandomUtil.randomInt(4, 6)*1000);
stopWatch.stop();
return Result.ok(stopWatch.getTotalTimeMillis());
}
/**
* 并行
*/
@GetMapping("/info")
Result info() throws Exception {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Future future = ThreadUtil.execAsync(() -> {
StopWatch stopWatch1 = new StopWatch();
stopWatch1.start();
Thread.sleep(RandomUtil.randomInt(2, 4)*1000);
stopWatch1.stop();
return stopWatch1.getTotalTimeMillis();
});
Future future1 = ThreadUtil.execAsync(() -> {
StopWatch stopWatch1 = new StopWatch();
stopWatch1.start();
Thread.sleep(RandomUtil.randomInt(4, 6)*1000);
stopWatch1.stop();
return stopWatch1.getTotalTimeMillis();
});
System.out.println(future.get());
System.out.println(future1.get());
stopWatch.stop();
return Result.ok(stopWatch.getTotalTimeMillis());
}
本文章为原创,未经允许不得转载