线程结束侦听器。JAVA

线程结束侦听器。JAVA,java,multithreading,actionlistener,Java,Multithreading,Actionlistener,Java中是否有侦听器来处理某些线程已结束的情况? 大概是这样的: Future<String> test = workerPool.submit(new TestCalalble()); test.addActionListener(new ActionListener() { public void actionEnd(Ac

Java中是否有侦听器来处理某些线程已结束的情况? 大概是这样的:

Future<String> test = workerPool.submit(new TestCalalble());
test.addActionListener(new ActionListener()               
   {                                                         
    public void actionEnd(ActionEvent e)               
    {                                                        
        txt1.setText("Button1 clicked");                        
    }                                                        
   });
Future test=workerPool.submit(newtestcalalble());
test.addActionListener(新ActionListener()
{                                                         
公共无效actionEnd(ActionEvent e)
{                                                        
txt1.setText(“点击按钮1”);
}                                                        
});
我知道,这是不可能的处理像这样,但我想得到通知时,一些线程结束

通常我使用这个计时器类来检查每个未来的状态。但这不是一个好办法。 谢谢

有你可以用的

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

就我个人而言,我更喜欢番石榴汁。

不。这样的听众并不存在。 但你有两个解决方案

  • 添加代码,通知您线程已在
    run()
    方法的末尾完成
  • 使用
    Callable
    接口返回类型为
    Future
    的结果。您可以询问Future状态是什么,并使用blocked方法
    get()
    检索结果
  • 您有一个由Thread类为此定义的join()方法。但是,在并发API情况下,您无法直接看到执行可调用线程的线程。

    这里是一个极客监听器。非常不建议使用,但是,有趣和聪明

    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
        }
    });
    
    通过幻影可以更好地达到效果

    希望你有一个小小的微笑:)



    旁注:您要求的不是线程结束,而是任务完成事件,最好是重写
    decoriteTask
    afterExecute

    ,您可以实现观察者模式来报告完成情况

    public interface IRunComplete {
        public void reportCompletion(String message);
    }
    
    让线程调用者实现这个接口

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

    使用以下示例:

    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);
    
        }
    }
    
    公共类主{
    公共静态void main(字符串[]args){
    CompletionListener completedListener=count->System.out.println(“最终计数值:”+count);
    HeavyWorkRunnable作业=新的HeavyWorkRunnable(completedListener);
    线程otherThread=新线程(作业);
    otherThread.start();
    }
    静态类HeavyWorkRunnable实现Runnable{
    CompletionListener CompletionListener;
    公共重量级Runnable(CompletionListener CompletionListener){
    this.completionListener=completionListener;
    }
    @凌驾
    公开募捐{
    整数计数=0;
    对于(int i=0;i<10;i++){
    试一试{
    睡眠(1000);
    }捕捉(中断异常e){
    e、 printStackTrace();
    }
    System.out.println(“时钟滴答声”#“+i);
    计数+=1;
    }
    if(completionListener!=null){
    completionListener.onCompleted(计数);
    }
    }
    }
    @功能接口
    接口完成侦听器{
    未完成的无效(整数计数);
    }
    }
    
    我还可以从ThreadPoolExecutor类重写afterExecute()方法。很高兴知道。我没有用番石榴,但似乎我应该用。。。怎么说呢。你应该。真的。:)“take()-检索并删除表示下一个已完成任务的未来,如果还没有任务,则等待。@”但我希望异步工作,因此它不适合Guava的+1。是的,你绝对应该使用它。Great tools.makeListenable()现在已被弃用甚至删除:“希望使用SettableFuture、MoreExecutors.listeningDecorator(java.util.concurrent.ExecutorService)创建ListenableFuture实例”,ListenableFutureTask,AbstractFuture和其他实用程序,而不是创建普通的将来实例,以便在事后升级到ListenableFuture。如果这不可能,makeListenable的功能现在可以作为JdkFutureAdapters.listenInPoolThread(java.util.concurrent.Future)使用。“我试图如实回答这个问题:“Java中有没有监听器可以处理某些线程已经结束的问题?”而不必进入j.u.c.或Guava或其他构建在核心语言之上的任何东西。
    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);
    
        }
    }