如何让Callable等到执行? [英] How to make Callable wait till execution?

查看:54
本文介绍了如何让Callable等到执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用

FutureTask<Integer> task = new FutureTask<Integer>(new MyCallable(name, type));
pool = Executors.newSingleThreadExecutor();
pool.submit(task);

我想知道 pool.submit(task) 之后是继续执行还是等待 callable 完成执行?

I want to know Is execution is continue after pool.submit(task) or It will wait for callable to complete its execution?

简而言之,我只想知道是否有类似 thread.join() 的 Callable 方法?

In short I just want to know is there any method like thread.join() for Callable?

推荐答案

... 是否有类似 thread.join() 的 Callable 方法?

... is there any method like thread.join() for Callable?

pool.submit(callable) 方法返回一个 Future,如果线程在池中可用,它将立即开始执行.要执行join,您可以调用与线程连接的future.get(),返回call() 方法返回的值.需要注意的是,如果 call() 方法抛出,get() 可能会抛出 ExecutionException.

The pool.submit(callable) method returns a Future and will start executing immediately if the threads are available in the pool. To do a join, you can call future.get() which joins with the thread, returning the value returned by the call() method. It is important to note that get() may throw an ExecutionException if the call() method threw.

您不需要将您的Callable 包装在FutureTask 中.线程池为你做这件事.所以你的代码是:

You do not need to wrap your Callable in a FutureTask. The thread-pool does that for you. So your code would be:

pool = Executors.newSingleThreadExecutor();
Future<String> future = pool.submit(new MyCallable(name, type));

// now you can do something in the foreground as your callable runs in the back

// when you are ready to get the background task's result you call get()
// get() waits for the callable to return with the value from call
// it also may throw an exception if the call() method threw
String value = future.get();

这当然是如果您的 MyCallable 实现了 Callable.Future 将匹配您的 Callable 的任何类型.

This is if your MyCallable implements Callable<String> of course. The Future<?> will match whatever type your Callable is.

这篇关于如何让Callable等到执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆