如何让Callable等到执行?
我有一个Callable,我调用了它
FutureTask task = new FutureTask(new MyCallable(name, type)); pool = Executors.newSingleThreadExecutor(); pool.submit(task);
我想知道在pool.submit(task)
之后执行是否继续,或者它将等待callable完成执行?
总之,我只是想知道是否有像Callable的thread.join()
这样的方法?
…有没有像Callable的thread.join()这样的方法?
pool.submit(callable)
方法返回一个Future
,如果池中的线程可用,它将立即开始执行。 要进行join
,可以调用与线程连接的future.get()
,返回call()
方法返回的值。 重要的是要注意,如果call()
方法抛出, get()
可能会抛出ExecutionException
。
您不需要在FutureTask
包装Callable
。 线程池为您做到了这一点。 所以你的代码是:
pool = Executors.newSingleThreadExecutor(); Future 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
任何类型。
task.get()
(任务是FutureTask
)期望当前线程等待线程池完成托管任务。
此方法最终返回具体结果或抛出相同的已检查exception(尽管包装到ExecutionException中),作业线程将在其任务期间抛出该exception。