当一个接口,需要返回多个数据,且每个数据获取的逻辑较为复杂,执行时间较长,那么如果同步去获取的话,这个接口的响应时间会很长,如果异步执行则会快很多
@Override
public Result location() throws Exception {
//创建线程池
ExecutorService executorService = Executors.newFixedThreadPool(3);
//创建计数器
CountDownLatch countDownLatch = new CountDownLatch(3);
//执行线程1
Future<List<Map>> lowerLevel = executorService.submit(() -> {
try {
return 结果1;
}finally {
//使latch的值减1,如果减到了0,则会唤醒所有等待在这个latch上的线程。
countDownLatch.countDown();
}
});
//执行线程2
Future<List<Map>> upperLevel = executorService.submit(() -> {
try {
return 结果2;
} finally {
countDownLatch.countDown();
}
});
//执行线程3
Future<Map> areaLocationGeoJson = executorService.submit(() -> {
try {
return 结果3;
} finally {
countDownLatch.countDown();
}
});
//使当前线程进入同步队列进行等待,直到latch的值被减到0或者当前线程被中断,才会被唤醒。
countDownLatch.await();
//拼装数据
Map result = new HashMap();
result.put("areaLocationGeoJson",areaLocationGeoJson.get());
result.put("upperLevel",upperLevel.get());
result.put("lowerLevel",lowerLevel.get());
//返回最终结果
return Result.ok(result);
}