[英]How to make Callable wait till execution?
I have One Callable which I invoked using 我有一个使用我调用的可调用对象
FutureTask<Integer> task = new FutureTask<Integer>(new MyCallable(name, type));
pool = Executors.newSingleThreadExecutor();
pool.submit(task);
I want to know Is execution is continue after pool.submit(task)
or It will wait for callable to complete its execution? 我想知道是否在
pool.submit(task)
之后继续执行,还是将等待pool.submit(task)
用以完成其执行?
In short I just want to know is there any method like thread.join()
for Callable? 简而言之,我只想知道是否有诸如Callable的
thread.join()
类的方法?
... is there any method like thread.join() for Callable?
...是否有像thread.join()这样的可调用方法?
The pool.submit(callable)
method returns a Future
and will start executing immediately if the threads are available in the pool. pool.submit(callable)
方法返回一个Future
,如果线程在池中可用,将立即开始执行。 To do a join
, you can call future.get()
which joins with the thread, returning the value returned by the call()
method. 要进行
join
,您可以调用与线程连接的future.get()
,返回由call()
方法返回的值。 It is important to note that get()
may throw an ExecutionException
if the call()
method threw. 重要的是要注意,如果
call()
方法抛出异常, get()
可能抛出ExecutionException
。
You do not need to wrap your Callable
in a FutureTask
. 您无需将
Callable
包装在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();
This is if your MyCallable
implements Callable<String>
of course. 当然,这是如果您的
MyCallable
实现了Callable<String>
的情况。 The Future<?>
will match whatever type your Callable
is. Future<?>
将匹配您的Callable
类型。
task.get()
(task being a FutureTask
) expects the current thread to wait for the completion of the managed task by the thread pooler. task.get()
(任务为FutureTask
)期望当前线程等待线程池管理器完成托管任务。
This method ends up returning either a concrete result or throwing the same checked exception (although wrapped into an ExecutionException) that the job thread would throw during its task. 此方法最终返回一个具体结果,或者抛出与作业线程在其任务期间将抛出的相同的检查异常(尽管已包装到ExecutionException中)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.