简体   繁体   English

线程结束监听器。 Java的

[英]Thread end listener. Java

Are there any Listeners in Java to handle that some thread have been ended? 是否有Java中的监听器来处理某些线程已经结束? 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. 我知道,这样处理是不可能的,但我想在一些线程结束时得到通知。

Usually I used for this Timer class with checking state of each Future. 通常我用这个Timer类来检查每个Future的状态。 but it is not pretty way. 但这不是很好的方式。 Thanks 谢谢

There is CompletionService you can use. 您可以使用CompletionService

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

Another alternative is to use ListenableFuture from Guava. 另一种方法是使用Guava的ListenableFuture

Code example: 代码示例:

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

Personally, I like Guava solution better. 就个人而言,我更喜欢番石榴解决方案。

You can implement Observer Pattern to report completion. 您可以实现Observer Pattern来报告完成情况。

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

Let the Thread caller implement this interface. 让Thread调用者实现此接口。

and in run() method you call this method at the end. 在run()方法中,最后调用此方法。 So now you exactly knows when this thread gonna end. 所以现在你确切地知道这个线程何时会结束。

Try it. 试试吧。 I am actually using this and it's working fine. 我实际上正在使用它,它工作正常。

Without adding a lot of extra code you can make a quick listener thread yourself as follows: 在不添加大量额外代码的情况下,您可以自己制作一个快速监听线程,如下所示:

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

Here is a geekish listener. 这是一个极端的倾听者。 Highly unadvisible to use but, funny and clever 非常不明智的使用,但有趣和聪明

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

The effect can be achived via PhantomRefernce better 可以通过PhantomRefernce更好地实现这种效果

hope you have a little smile :) 希望你有一点微笑:)


Side note: what you ask is NOT thread end , but task completion event and the best is overriding either decorateTask or afterExecute 旁注:你问的不是线程结束 ,但是任务完成事件和最好的是覆盖decorateTaskafterExecute

No. Such listener does not exist. 不,这样的听众不存在。 But you have 2 solutions. 但是你有2个解决方案。

  1. Add code that notifies you that thread is done in the end of run() method 添加代码,通知您线程在run()方法结束时完成
  2. Use Callable interface that returns result of type Future . 使用返回Future类型结果的Callable接口。 You can ask Future what the status is and use blocked method get() to retrieve result 您可以询问Future状态是什么,并使用阻塞方法get()来检索结果

You have a join() method defined by Thread class for that. 你有一个Thread类定义的join()方法。 However, you don't have direct visibility to a thread executing your Callable in concurrency API case.. 但是,您无法直接查看在并发API情况下执行Callable的线程。

Use this Example: 使用此示例:

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