繁体   English   中英

Java:创建一个多线程阅读器

[英]Java: Creating a multi threaded reader

我正在创建一个阅读器应用程序。 读者根据参数识别要读取的文件,进行一些处理并将结果返回给调用者。

我试图使这个多线程,以便可以处理多个请求。 我认为它很简单但后来意识到它有一些复杂性。 即使我使用执行程序服务创建线程,我仍然需要将结果返回给调用者。 所以这意味着等待线程执行。

我能想到的唯一方法是写入一些常见位置或数据库,然后让调用者从那里选择结果。 有可能有办法吗?

也许ExecutorCompletionService可以帮助您。 完成后,提交的任务将放在队列中。 您可以使用方法take或poll,具体取决于您是否要等待任务在完成队列上可用。

ExecutorCompletionService javadoc

使用大小> 1的线程池的ExecutorService ,发布自定义的FutureTask衍生物,它们覆盖done()方法以向UI发送任务完成信号:

public class MyTask extends FutureTask<MyModel> {
  private final MyUI ui;

  public MyTask(MyUI toUpdateWhenDone, Callable<MyModel> taskToRun) {
    super(taskToRun);
    ui=toUpdateWhenDone;
  }
  @Override
  protected void done() {
    try {
      // retrieve computed result
      final MyModel computed=get();
      // trigger an UI update with the new model
      java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
           ui.setModel(computed); // set the new UI model
        }
      });
    }
    catch(InterruptedException canceled) {
       // task was canceled ... handle this case here
    }
    catch(TimeoutException timeout) {
      // task timed out (if there are any such constraints). 
      // will not happen if there are no constraints on when the task must complete
    }
    catch(ExecutionException error) { 
      // handle exceptions thrown during computation of the MyModel object...
      // happens if the callable passed during construction of the task throws an 
      // exception when it's call() method is invoked.
    }
  }
}

编辑:对于那些需要对信号状态更新更复杂的任务,它可能是用这种方式来创建自定义的SwingWorker衍生物和张贴那些在ExecutorService的一个好主意。 (您应该暂时不尝试同时运行多个SwingWorkers,因为当前的SwingWorker实现实际上不允许它。)

暂无
暂无

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

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