简体   繁体   English

如何通知调用者线程ExecutorService已完成任务

[英]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? 现在,当Runnable完成执行时,是否有Java的标准方式来通知调用程序线程它已经完成执行,而没有创建新的接口/监听器类?

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. submit回报Future在其上提交线程可以调用get阻塞,直到任务完成。

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. 您可以阻止返回的Future对象的get(),或者在其上轮询isDone()方法。 Alternatively, you could use the google guava library that has ListenableFuture . 或者,您可以使用具有ListenableFuture的google guava库。

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. 你可以看一件事是通过调用一个知道如何更新所需UI组件的方法来让runnable自己发出信号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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