java 事件源 监听器_使用事件侦听器作为Java 8 Stream源

可以在TaskResults周围构建一个Stream.看这个例子:

import java.util.Iterator;

import java.util.NoSuchElementException;

import java.util.Spliterator;

import java.util.Spliterators;

import java.util.concurrent.BlockingQueue;

import java.util.concurrent.LinkedBlockingQueue;

import java.util.stream.Stream;

import java.util.stream.StreamSupport;

/**

* Created for https://stackoverflow.com/q/27670421/1266906.

*/

public class AsyncToStream {

public static void main(String[] args) {

System.out.println("Unbuffered Test:");

AsyncTaskResultIterator taskListener1 = new AsyncTaskResultIterator<>();

new TaskResultGenerator(taskListener1,5).start();

taskListener1.unbufferedStream().forEach(System.out::println);

System.out.println("Buffered Test:");

AsyncTaskResultIterator taskListener2 = new AsyncTaskResultIterator<>();

new TaskResultGenerator(taskListener2,5).start();

taskListener2.bufferedStream().forEach(System.out::println);

}

/**

* This class wraps a sequence of TaskResults into an iterator upto the first TaskResult where {@code }isLastResult()} returns {@code true}

*/

public static class AsyncTaskResultIterator implements Iterator,TaskListener {

/**

* This acts as an asynchronous buffer so we can easily wait for the next TaskResult

*/

private final BlockingQueue blockingQueue;

/**

* Becomes {@code true} once {@code TaskResult.isLastResult()} is received

*/

private boolean ended;

public AsyncTaskResultIterator() {

blockingQueue = new LinkedBlockingQueue<>();

}

/**

* Waits on a new TaskResult and returns it as long as the prevIoUs TaskResult did not specify {@code isLastResult()}. Afterwards no more elements can be retrieved.

*/

@Override

public T next() {

if (ended) {

throw new NoSuchElementException();

} else {

try {

T next = blockingQueue.take();

ended = next.isLastResult();

return next;

} catch (InterruptedException e) {

throw new IllegalStateException("Could not retrieve next value",e);

}

}

}

@Override

public boolean hasNext() {

return !ended;

}

/**

* Enqueue another TaskResult for retrieval

*/

@Override

public void onTaskResult(T result) {

if (ended) {

throw new IllegalStateException("Already received a TaskResult with isLastResult() == true");

}

try {

blockingQueue.put(result);

} catch (InterruptedException e) {

throw new IllegalStateException("Could not enqueue next value",e);

}

}

/**

* Builds a Stream that acts upon the results just when they become available

*/

public Stream unbufferedStream() {

Spliterator spliterator = Spliterators.spliteratorUnknownSize(this,0);

return StreamSupport.stream(spliterator,false);

}

/**

* Buffers all results and builds a Stream around the results

*/

public Stream bufferedStream() {

Stream.Builder builder = Stream.builder();

this.forEachRemaining(builder);

return builder.build();

}

}

public static class TaskResultImpl implements TaskResult {

private boolean lastResult;

private String name;

public TaskResultImpl(boolean lastResult,String name) {

this.lastResult = lastResult;

this.name = name;

}

@Override

public String toString() {

return "TaskResultImpl{" +

"lastResult=" + lastResult +

",name='" + name + '\'' +

'}';

}

@Override

public boolean isLastResult() {

return lastResult;

}

}

public static interface TaskListener {

public void onTaskResult(T result);

}

public static interface TaskResult {

boolean isLastResult();

}

private static class TaskResultGenerator extends Thread {

private final TaskListener taskListener;

private final int count;

public TaskResultGenerator(TaskListener taskListener,int count) {

this.taskListener = taskListener;

this.count = count;

}

@Override

public void run() {

try {

for (int i = 1; i < count; i++) {

Thread.sleep(200);

taskListener.onTaskResult(new TaskResultImpl(false,String.valueOf(i)));

}

Thread.sleep(200);

taskListener.onTaskResult(new TaskResultImpl(true,String.valueOf(count)));

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

你没有提供你的TaskResult和TaskListener定义所以我自己编造了. AsyncTaskResultIterator仅适用于单个TaskResult-sequences.如果没有提供具有isLastResult()== true的TaskResult next(),那么无缓冲的Stream和缓冲的Stream生成将无休止地等待.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值