public static Integer getTotal1(){
try {
System.out.println("开始getTotal1");
Thread.sleep(6000);
System.out.println("结束getTotal1");
} catch (Exception e) {
e.printStackTrace();
}
return 1;
}
public static Integer getTotal2(){
try {
System.out.println("开始getTotal2");
Thread.sleep(3000);
System.out.println("结束getTotal2");
} catch (Exception e) {
e.printStackTrace();
}
return 3;
}
使用普通方式调用上面两个方法得到返回数据需要耗时9秒多, 一个方法6秒多,一个方法3秒多,
long start = System.currentTimeMillis();
System.err.print(getTotal1());
System.err.print(getTotal2());
long end = System.currentTimeMillis();
System.err.print("耗时=====>"+(end-start));
使用FutureTask 则只需要6秒多就可以得到两个方法的返回数据
long start = System.currentTimeMillis();
Callable ca1 = new Callable<Integer>(){
@Override
public Integer call() throws Exception {
return getTotal1();
}
};
FutureTask<Integer> recharge1 = new FutureTask<Integer>(ca1);
new Thread(recharge1).start();
Callable ca2 = new Callable<Integer>(){
@Override
public Integer call() throws Exception {
return getTotal2();
}
};
FutureTask<Integer> recharge2 = new FutureTask<Integer>(ca2);
new Thread(recharge2).start();
System.err.print(recharge1.get());
System.err.print("\n====================\n");
System.err.print(recharge2.get());
long end = System.currentTimeMillis();
System.err.print("耗时=====>"+(end-start));