【问题标题】:Java: Creating a multi threaded readerJava:创建多线程阅读器
【发布时间】:2011-11-28 09:26:29
【问题描述】:

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

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

我能想到的唯一方法是写入某个公共位置或数据库,然后让调用者从那里选择结果。有什么办法可以吗?

【问题讨论】:

  • 当提交到执行器服务时,你会得到一个未来,你为什么不等待它完成呢?
  • 谢谢Thomas,但这意味着这个过程需要等待Future的结果。
  • 因此您必须对来自进程的请求进行多线程处理。你从哪里得到它们? RPC/RMI/套接字?如果你能显示一些代码会很棒;)
  • “调用者”和工作线程之间的预期交互是什么?您似乎在表明调用者是异步的,即它提交请求并稍后轮询结果?
  • 调用将跨套接字。还没写代码。还在设计中:)

标签: java concurrency


【解决方案1】:

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

ExecutorCompletionService javadoc

【讨论】:

    【解决方案2】:

    使用具有大小 > 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 上可能是个好主意。 (您暂时不应该尝试同时运行多个 SwingWorker,因为当前的 SwingWorker 实现实际上不允许这样做。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-29
      • 2019-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-10
      • 1970-01-01
      • 2016-08-26
      相关资源
      最近更新 更多