[英]How does a Callable work under the hood? How is it possible for a callable object to return a value?
我试图了解Callable
如何在另一个线程上运行时返回一个值。
我在查看类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 statement
输出null?
如何将由单独线程运行的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();
...
}
<T> Future<T> submit(Callable<T> task)
:提交一个返回值的任务以执行并返回表示任务挂起结果的Future。 Future的get方法将在成功完成后返回任务的结果。 如果您想立即阻止等待任务,可以使用结构形式为result = exec.submit(aCallable).get();
问:在ExecutorService运行其线程之前,主线程是否可能运行,以便System.out语句打印为null?
- > Future <T> .get()在必要时等待计算完成,然后检索其结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.