Callable如何在引擎盖下工作?可调用对象如何返回值?

Rox*_*Rox 6 java multithreading

我试图了解如何Callable在一个不同的线程上运行时能够返回一个值.

我期待中的类Executors,AbstractExecutorService,ThreadPoolExecutor并且FutureTask,在所有可用的java.util.concurrent软件包.

您可以通过调用Executors中的方法(例如newSingleThreadExecutor())来创建ExecutorService对象.然后你可以传递一个Callable对象 ExecutorService.submit(Callable c).

由于该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    }
Run Code Online (Sandbox Code Playgroud)

如何将由单独线程运行的call方法中的整数返回到Integer对象(第3行),以便它可以通过System.out主线程(第7行)中的语句打印出来?

主线程是否有可能在ExecutorService运行其线程之前运行,以使System.out statementprint打印为null?

Gra*_*ray 8

如何将由单独线程运行的call方法中的整数返回给Integer对象

ExecutorService.submit(...)没有返回从对象call(),但它并返回Future<Integer>,您可以使用Future.get()方法来获取该对象.请参阅下面的示例代码.

在ExecutorService运行其线程之前是否可以运行主线程,以便System.out语句输出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();
   ...
}
Run Code Online (Sandbox Code Playgroud)

  • `Future.get()`做等待.在`FutureTask`里面我相信`acquireSharedInterruptibly(0)`然后调用`doAcquireSharedInterruptibly(...)`进行同步并等待.同步是用`volatile`完成的. (2认同)