本文介绍了线程结束监听器。 Java的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中是否有任何监听器可以处理某些线程已经结束?
这样的事情:

Are there any Listeners in Java to handle that some thread have been ended?Something like this:

Future<String> test = workerPool.submit(new TestCalalble());
test.addActionListener(new ActionListener()
   {
    public void actionEnd(ActionEvent e)
    {
        txt1.setText("Button1 clicked");
    }
   });

我知道,这样处理是不可能的,但是我希望在某些线程时得到通知结束。

I know, that it is impossible to deal like this, but I want to be notified when some thread ended.

通常我用这个Timer类来检查每个Future的状态。但这不是很好的方式。
谢谢

Usually I used for this Timer class with checking state of each Future. but it is not pretty way.Thanks

推荐答案

CompletionService<Result> ecs
       = new ExecutorCompletionService<Result>(e);
ecs.submit(new TestCallable());
if (ecs.take().get() != null) {
    // on finish
}

另一种方法是使用来自Guava。

Another alternative is to use ListenableFuture from Guava.

代码示例:

ListenableFuture future = Futures.makeListenable(test);
future.addListener(new Runnable() {
 public void run() {
   System.out.println("Operation Complete.");
   try {
     System.out.println("Result: " + future.get());
   } catch (Exception e) {
     System.out.println("Error: " + e.message());
   }
 }
}, exec);

就个人而言,我更喜欢Guava解决方案。

Personally, I like Guava solution better.

这篇关于线程结束监听器。 Java的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 13:50