繁体   English   中英

线程结束监听器。 Java的

[英]Thread end listener. Java

是否有Java中的监听器来处理某些线程已经结束? 像这样的东西:

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

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

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

您可以使用CompletionService

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

另一种方法是使用Guava的ListenableFuture

代码示例:

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);

就个人而言,我更喜欢番石榴解决方案。

您可以实现Observer Pattern来报告完成情况。

public interface IRunComplete {
    public void reportCompletion(String message);
}

让Thread调用者实现此接口。

在run()方法中,最后调用此方法。 所以现在你确切地知道这个线程何时会结束。

试试吧。 我实际上正在使用它,它工作正常。

在不添加大量额外代码的情况下,您可以自己制作一个快速监听线程,如下所示:

//worker thread for doings
Thread worker = new Thread(new Runnable(){ 
    public void run(){/*work thread stuff here*/}
});
worker.start();
//observer thread for notifications
new Thread(new Runnable(){
    public void run(){
    try{worker.join();}
    catch(Exception e){;}
    finally{ /*worker is dead, do notifications.*/}
}).start();

这是一个极端的倾听者。 非常不明智的使用,但有趣和聪明

Thread t = ...
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler(){
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        t.getThreadGroup().uncaughtException(t, e);//this is the default behaviour
    }       
    protected void finalize() throws Throwable{
        //cool, we go notified
      //handle the notification, but be worried, it's the finalizer thread w/ max priority
    }
});

可以通过PhantomRefernce更好地实现这种效果

希望你有一点微笑:)


旁注:你问的不是线程结束 ,但是任务完成事件和最好的是覆盖decorateTaskafterExecute

不,这样的听众不存在。 但是你有2个解决方案。

  1. 添加代码,通知您线程在run()方法结束时完成
  2. 使用返回Future类型结果的Callable接口。 您可以询问Future状态是什么,并使用阻塞方法get()来检索结果

你有一个Thread类定义的join()方法。 但是,您无法直接查看在并发API情况下执行Callable的线程。

使用此示例:

public class Main {

    public static void main(String[] args) {

        CompletionListener completedListener = count -> System.out.println("Final Count Value: " + count);

        HeavyWorkRunnable job = new HeavyWorkRunnable(completedListener);

        Thread otherThread = new Thread(job);
        otherThread.start();

    }

    static class HeavyWorkRunnable implements Runnable {

        CompletionListener completionListener;

        public HeavyWorkRunnable(CompletionListener completionListener) {
            this.completionListener = completionListener;
        }


        @Override
        public void run() {

            int count = 0;

            for (int i = 0; i < 10; i++) {

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Clock Tick #"+i);

                count += 1;

            }

            if (completionListener != null) {
                completionListener.onCompleted(count);
            }
        }
    }

    @FunctionalInterface
    interface CompletionListener {

        void onCompleted(int count);

    }
}

暂无
暂无

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

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