在实际项目中,经常需要将查询获得的数据封装为合适的数据结构返回给前端呈现,如果一个接口中,存在多个查询,此时如果串行执行,消耗的时间为多个查询耗时的总和,效率不高,示例代码如下:
public static void main(String[] args) throws Exception {
/**
* 耗时5005 ms
*/
long start = System.currentTimeMillis();
System.out.println("A start");
Thread.sleep(2000);
System.out.println("A end");
System.out.println("B start");
Thread.sleep(3000);
System.out.println("B end");
System.out.println(System.currentTimeMillis() - start);
}
此时采用Runnable的大表兄Callable,再加上多线程,可以并行的执行多个查询,提高效率。
public static void main(String[] args) throws Exception {
/**
* 耗时3003ms 即以最长的时间为准
*/
ExecutorService pool = Executors.newFixedThreadPool(2);
long start = System.currentTimeMillis();
try {
Callable<Void> a = new Callable<Void>() {