簡體   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