在实际项目中,经常需要将查询获得的数据封装为合适的数据结构返回给前端呈现,如果一个接口中,存在多个查询,此时如果串行执行,消耗的时间为多个查询耗时的总和,效率不高,示例代码如下:
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>() {
@Override
public Void call() throws Exception {
System.out.println("A start");
Thread.sleep(2000);
System.out.println("A end");
return null;
}
};
Callable<Void> b = new Callable<Void>() {
@Override
public Void call() throws Exception {
System.out.println("B start");
Thread.sleep(3000);
System.out.println("B end");
return null;
}
};
Future<Void> f1 = pool.submit(a);
Future<Void> f2 = pool.submit(b);
f1.get();
f2.get();
} catch (Exception e) {
e.printStackTrace();
} finally {
pool.shutdown();
}
System.out.println(System.currentTimeMillis() - start);
}
Callable执行call方法后,会有一个返回值,采用Future,可以获取此返回值。