加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:53:29 所属栏目:Java 来源:网络整理
导读:我试图了解Callable如何在另一个线程上运行时返回一个值. 我在查看类Executors,AbstractExecutorService,ThreadPoolExecutor和FutureTask,所有这些都在java.util.concurrent包中提供. 您可以通过调用Executors中的方法(例如newSingleThreadExecutor())来创建
我试图了解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语句输出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();
   ...
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读