简体   繁体   中英

How to signal the caller thread that ExecutorService has finished a task

From the main thread:

executorService.submit(new Runnable() { ... });

Now when Runnable has finished executing, is there the Java's standard way of signaling the caller thread that it has finished executing, without making a new interface/listener class?

Bonus points if the signal can be emitted from the caller thread.

submit returns a Future on which the submitting thread can call get to block until the task completes.

Future<?> future = executor.submit(new Runnable() { ... });
future.get();

You can block on get() of the Future object that is returned, or poll the isDone() method on it. Alternatively, you could use the google guava library that has ListenableFuture .

I am not sure of your implementation and how many threads will be running simultaneously, so this may not work. One thing you could take a look at is to have the runnable itsself signal it is completed by calling a method that knows how to update the UI component that is needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM