有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程线程端侦听器。JAVA

Java中是否有侦听器来处理某些线程已结束的情况? 比如:

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

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

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


共 (6) 个答案

  1. # 1 楼答案

    线程类为此定义了一个join()方法。然而,在并发API的情况下,您无法直接看到执行可调用的线程

  2. # 2 楼答案

    CompletionService可以使用

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

    另一种选择是使用番石榴中的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);
    

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

  3. # 3 楼答案

    无需添加大量额外代码,您可以自己创建一个快速侦听器线程,如下所示:

    //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();
    
  4. # 4 楼答案

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

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

    通过幻影可以更好地达到效果

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


    旁注:你问的不是线程结束,而是任务完成事件,最好的是重写decorateTaskafterExecute

  5. # 5 楼答案

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

    1. 添加代码,通知您线程在run()方法的末尾完成
    2. 使用Callable接口返回Future类型的结果。您可以询问Future状态是什么,并使用blocked方法get()检索结果
  6. # 6 楼答案

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

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

    让线程调用者实现这个接口

    在run()方法中,最后调用这个方法。现在你知道这条线什么时候结束了

    试试看。我正在用这个,效果很好