我在查看类Executors,AbstractExecutorService,ThreadPoolExecutor和FutureTask,所有这些都在java.util.concurrent包中提供.
您可以通过调用Executors中的方法(例如newSingleThreadExecutor())来创建ExecutorService对象.然后,您可以使用ExecutorService.submit(Callable c)传递Callable对象.
由于call()方法由ExecutorService提供的线程运行,返回的对象在哪里“跳转”回调用线程?
看看这个简单的例子:
1 ExecutorService executor = Executors.newSingleThreadExecutor(); 2 public static void main(String[] args) { 3 Integer i = executor.submit(new Callable<Integer>(){ 4 public Integer call() throws Exception { 5 return 10; 6 } 7 }).get(); 8 System.out.print("Returns: " + i + " Thread: " + Thread.currentThread.getName()); 9 // prints "10 main" 10 }
如何将由单独线程运行的call方法中的整数返回到Integer对象(第3行),以便它可以由主线程(第7行)中的System.out语句打印?
在ExecutorService运行其线程之前是否可以运行主线程,以便System.out语句输出null?
解决方法
How is it possible that the integer in the call method,which is run by a separate thread,is returned to the Integer object
ExecutorService.submit(…)不会从call()返回该对象,但它会返回Future< Integer>并且您可以使用Future.get()方法来获取该对象.请参阅下面的示例代码.
Isn´t it possible for the main thread to be run before the ExecutorService has run its thread,so that the System.out statement prints null?
不,未来的get()方法会等到作业完成.如果call()返回null,则get()否则将返回(并打印)10保证.
Future<Integer> future = executor.submit(new Callable<Integer>(){ public Integer call() throws Exception { return 10; } }); try { // get() waits for the job to finish before returning the value // it also might throw an exception if your call() threw Integer i = future.get(); ... } catch (ExecutionException e) { // this cause exception is the one thrown by the call() method Exception cause = e.getCause(); ... }