package接口聚合;importjava.util.concurrent.Callable;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.concurrent.FutureTask;
public classdemo {public static ExecutorService executorService = Executors.newFixedThreadPool(5);public static voidmain(String[] args) {
demo d= newdemo();
System.out.println(d.getABInfoOnWebOld());
System.out.println(d.getABInfoOnWebNew());
}//模拟WEB接口 ---接口串行
publicString getABInfoOnWebOld(){long before =System.currentTimeMillis();
String s=RemoteService.serviceA();
String s1=RemoteService.serviceB();long cost = System.currentTimeMillis() -before;return s+":"+s1+"cost :"+cost;
}//模拟WEB接口 ---接口集合
publicString getABInfoOnWebNew(){long before =System.currentTimeMillis();
Callable taskA = new Callable() {public String call() throwsException {returnRemoteService.serviceA();
}
};
Callable taskB = new Callable() {public String call() throwsException {returnRemoteService.serviceB();
}
};
FutureTask futureTaskA= newFutureTask(taskA);
FutureTask futureTaskB= newFutureTask(taskB);
executorService.submit(futureTaskA);
executorService.submit(futureTaskB);
String result= "";try{
result= futureTaskA.get() +":"+futureTaskB.get();long cost = System.currentTimeMillis() -before;
result= result+"cost:"+cost;
}catch(Exception e) {
e.printStackTrace();
}finally{
executorService.shutdown();
}returnresult;
}//模拟远程服务
static classRemoteService{public staticString serviceA(){try{
Thread.sleep(2000L);
}catch(InterruptedException e) {
e.printStackTrace();
}return "A";
}public staticString serviceB(){try{
Thread.sleep(3000L);
}catch(InterruptedException e) {
e.printStackTrace();
}return "B";
}
}
}