多线程线程端侦听器。JAVA
Java中是否有侦听器来处理某些线程已结束的情况? 比如:
Future<String> test = workerPool.submit(new TestCalalble());
test.addActionListener(new ActionListener()
{
public void actionEnd(ActionEvent e)
{
txt1.setText("Button1 clicked");
}
});
我知道,这样做是不可能的,但我希望在某些线程结束时得到通知
通常我会在这个计时器类中检查每个未来的状态。但这不是个好办法。 谢谢
# 1 楼答案
线程类为此定义了一个join()方法。然而,在并发API的情况下,您无法直接看到执行可调用的线程
# 2 楼答案
有CompletionService可以使用
另一种选择是使用番石榴中的ListenableFuture
代码示例:
就我个人而言,我更喜欢番石榴汁
# 3 楼答案
无需添加大量额外代码,您可以自己创建一个快速侦听器线程,如下所示:
# 4 楼答案
这是一个极客的听众。非常不建议使用,但是非常有趣和聪明
通过幻影可以更好地达到效果
希望你有一个小小的微笑:)
旁注:你问的不是线程结束,而是任务完成事件,最好的是重写
decorateTask
或afterExecute
# 5 楼答案
不,这样的倾听者并不存在。 但你有两个解决方案
run()
方法的末尾完成Callable
接口返回Future
类型的结果。您可以询问Future状态是什么,并使用blocked方法get()
检索结果# 6 楼答案
您可以实现观察者模式来报告完成情况
让线程调用者实现这个接口
在run()方法中,最后调用这个方法。现在你知道这条线什么时候结束了
试试看。我正在用这个,效果很好