首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Java 8迭代流操作

Java 8迭代流操作
EN

Stack Overflow用户
提问于 2014-01-23 20:09:06
回答 1查看 1.4K关注 0票数 2

我想要执行一个流,在这个流中,来自流的输出在相同的操作中被用作同一流的源。

目前,我使用队列执行这类操作;我删除一个项,处理它,并将任何需要进一步处理的结果添加回队列。以下是这类事情的两个例子:

代码语言:javascript
运行
复制
Queue<WorkItem> workQueue = new Queue<>(workToDo);
while(!workQueue.isEmpty()){
    WorkItem item = workQueue.remove();
    item.doOneWorkUnit();
    if(!item.isDone()) workQueue.add(item);
}

Queue<Node> nodes = new Queue<>(rootNodes);
while(!nodesLeft.isEmpty()){
    Node node = nodes.remove();
    process(node);
    nodes.addAll(node.children());
}

我可以想象,第一项工作可以同时进行,例如:

代码语言:javascript
运行
复制
try {
    LinkedBlockingQueue<WorkItem> workQueue = new LinkedBlockingQueue<>();
    Stream<WorkItem> reprocess = Stream.generate(() -> workQueue.remove()).parallel();

    Stream.concat(workToDo.parallelstream(), reprocess)
          .filter(item -> {item.doOneWorkUnit(); return !item.isDone();})
          .collect(Collectors.toCollection(() -> workQueue));
} catch (NoSuchElementException e){}

第二项是:

代码语言:javascript
运行
复制
try {
    LinkedBlockingQueue<Node> reprocessQueue = new LinkedBlockingQueue<>();
    Stream<WorkItem> reprocess = Stream.generate(() -> nodes.remove()).parallel();

    Stream.concat(rootNodes.parallelStream(), reprocess)
          .filter(item -> {process(item); return true;})
          .flatMap(node -> node.children().parallelStream())
          .collect(Collectors.toCollection(() -> reprocessQueue));
} catch (NoSuchElementException e){}

然而,这些感觉就像一个乱七八糟的解决方案,我不喜欢使用异常。有人有更好的方法来做这种事吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-11 20:00:02

为了使工作并行,我将使用标准的java.util.concurrent.Executor。若要将任务返回到工作队列,请在每个任务的代码末尾添加executor.execute(this)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21318304

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档