java多线程(ExecutorService)

ExecutorService exec = null;
List<IbeFlightInfo> ibeFlightInfo = new ArrayList<IbeFlightInfo>();
TransferVO[] b2gFlights = new TransferVO[]{};
try {
exec = Executors.newFixedThreadPool(2);
Callable IBEcall = new IBEGetFlightThread(request);
Callable B2Gcall = new B2GGetFlightThread(request.getDepAirport(), request.getArrAirport(),request.getDepDate());

/*

submit(Callable)
方法 submit(Callable) 和方法 submit(Runnable) 比较类似,但是区别则在于它们接收不同的参数类型。Callable 的实例与 Runnable 的实例很类似,但是 Callable 的 call() 方法可以返回壹個结果。方法 Runnable.run() 则不能返回结果。

Callable 的返回值可以从方法 submit(Callable) 返回的 Future 对象中获取。

*/


Future<Object> IBEFuture = exec.submit(IBEcall);
Future<Object> B2GFuture = exec.submit(B2Gcall);
int second = 0;
while (!IBEFuture.isDone() && !B2GFuture.isDone()) {
TimeUnit.MILLISECONDS.sleep(1000);
second += 1;
}

ibeFlightInfo = (List<IbeFlightInfo>) IBEFuture.get();
b2gFlights = (TransferVO[]) B2GFuture.get();

System.out.println("共用時(秒):" + second);
} catch (Exception e) {
e.printStackTrace();
} finally {

/*

为了关闭在 ExecutorService 中的线程,你需要调用 shutdown() 方法。ExecutorService 并不会马上关闭,而是不再接收新的任务,壹但所有的线程结束执行当前任务,ExecutorServie 才会真的关闭。所有在调用 shutdown() 方法之前提交到 ExecutorService 的任务都会执行。
如果你希望立即关闭 ExecutorService,你可以调用 shutdownNow() 方法。这個方法会尝试马上关闭所有正在执行的任务,并且跳过所有已经提交但是还没有运行的任务。但是对于正在执行的任务,是否能够成功关闭它是无法保证的,有可能他们真的被关闭掉了,也有可能它会壹直执行到任务结束。这是壹個最好的尝试。

*/


exec.shutdown();
}

原文地址:https://www.cnblogs.com/flord/p/5920910.html