How to make Callable wait till execution?

2019-06-11 09:00发布

问题:

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.