package 接口聚合; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; public class demo { public static ExecutorService executorService = Executors.newFixedThreadPool(5); public static void main(String[] args) { demo d = new demo(); System.out.println(d.getABInfoOnWebOld()); System.out.println(d.getABInfoOnWebNew()); } //模拟WEB接口 ---接口串行 public String getABInfoOnWebOld(){ long before = System.currentTimeMillis(); String s = RemoteService.serviceA(); String s1 = RemoteService.serviceB(); long cost = System.currentTimeMillis() - before; return s+":"+s1+"cost :"+cost; } //模拟WEB接口 ---接口集合 public String getABInfoOnWebNew(){ long before = System.currentTimeMillis(); Callable<String> taskA = new Callable<String>() { public String call() throws Exception { return RemoteService.serviceA(); } }; Callable<String> taskB = new Callable<String>() { public String call() throws Exception { return RemoteService.serviceB(); } }; FutureTask futureTaskA = new FutureTask(taskA); FutureTask futureTaskB = new FutureTask(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(); } return result; } //模拟远程服务 static class RemoteService{ public static String serviceA(){ try { Thread.sleep(2000L); } catch (InterruptedException e) { e.printStackTrace(); } return "A"; } public static String serviceB(){ try { Thread.sleep(3000L); } catch (InterruptedException e) { e.printStackTrace(); } return "B"; } } }