Java:如何从线程返回中间结果 [英] Java : How to return intermediate results from a Thread

查看:238
本文介绍了Java:如何从线程返回中间结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Java 7 我正在尝试构建一个监视程序,该监视程序监视数据存储(某种收集类型),然后在某些时候从中返回某些项. 在这种情况下,它们是时间戳,当时间戳超过当前时间时,我希望将其返回到起始线程.请参见下面的代码.

Using Java 7 I am trying to build a watcher that watches a data store (some collection type) and then will return certain items from it at certain points. In this case they are time stamps, when a timestamp passes the current time I want it to be returned to the starting thread. Please see code below.

@Override
public void run() {
  while (!data.isEmpty()) {
    for (LocalTime dataTime : data) {
      if (new LocalTime().isAfter(dataTime)) {
        // return a result but continue running
      }
    }
  }
}

我已经阅读了有关future和callable的内容,但是它们似乎在返回时停止了线程.

I have read about future and callables, but they seem to stop the thread on a return.

我不是特别想返回值并停止线程,然后在使用callable时启动另一个任务,除非这是最好的方法.

I do not particularly want to return a value and stop the thread then start another task if using callable, unless it is the best way.

寻找此内容的最佳技术是什么?这样做的范围似乎很广.

What are the best techniques to look for this? There seem to be such a wide range of doing it.

谢谢

推荐答案

您可以将中间结果放入

You can put the intermediate results in a Blocking Queue so that the results are available to consumer threads as and when they are made available :

private final LinkedBlockingQueue<Result> results = new LinkedBlockingQueue<Result>();

@Override
public void run() {
  while (!data.isEmpty()) {
    for (LocalTime dataTime : data) {
      if (new LocalTime().isAfter(dataTime)) {
        results.put(result);
      }
    }
  }
}

public Result takeResult() {
    return results.take(); 
}

消费者线程可以简单地调用takeResult方法来使用中间结果.使用阻塞队列的优点是您不必重新发明轮子,因为这看起来像可以使用阻塞数据结构解决的典型生产者-消费者方案.

Consumer threads can simply call the takeResult method to use the intermediate results. The advantage of using a Blocking Queue is that you don't have to reinvent the wheel since this looks like a typical producer-consumer scenario that can be solved using a blocking data structure.

注意在这里,Result可以是代表中间结果对象的` POJO .

Note Here, Result can be a `POJO that represents the intermediate result object.

这篇关于Java:如何从线程返回中间结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆