How to make Callable wait till execution?

纵饮孤独 提交于 2019-12-08 12:13:34

问题


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?

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


回答1:


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

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.

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();

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




回答2:


task.get() (task being a FutureTask) expects the current thread to wait for the completion of the managed task by the thread pooler.

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.



来源:https://stackoverflow.com/questions/12621041/how-to-make-callable-wait-till-execution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!