Java 9 通过引入一些接口来支持创建反应式流: Publisher、Subscriber、Subscription和实现Publisher 接口的SubmissionPublisher 类。每个接口可以根据反应式流的原则扮演不同的角色。
我们可以使用Subscriber 接口订阅由publisher发布的数据。我们需要实现Subscriber 接口并为抽象方法提供实现。
import java.util.concurrent.Flow; import java.util.concurrent.SubmissionPublisher; import java.util.stream.IntStream; public class SubscriberImplTest { public static class Subscriber implements <strong>Flow.Subscriber<Integer></strong> { private <strong>Flow.Subscription</strong> subscription; private boolean isDone; <strong> @Override</strong> public void <strong>onSubscribe</strong>(Flow.Subscription subscription) { System.out.println("Subscribed"); this.subscription = subscription; this.subscription.request(1); } <strong>@Override</strong> public void <strong>onNext</strong>(Integer item) { System.out.println("Processing " + item); this.subscription.request(1); } <strong>@Override</strong> public void <strong>onError</strong>(Throwable throwable) { throwable.printStackTrace(); } <strong>@Override</strong> public void <strong>onComplete()</strong> { System.out.println("Processing done"); isDone = true; } } public static void main(String args[]) throws InterruptedException { <strong>SubmissionPublisher<Integer></strong> publisher = new <strong>SubmissionPublisher<></strong><strong>()</strong>; <strong>Subscriber </strong>subscriber = new <strong>Subscriber()</strong>; publisher.subscribe(subscriber); <strong>IntStream</strong> intData = <strong>IntStream.rangeClosed</strong>(1, 10); intData.forEach(<strong>publisher::submit</strong>); publisher.<strong>close()</strong>; while(!subscriber.isDone) { Thread.sleep(10); } System.out.println("Done"); } }
<strong>Subscribed Processing 1 Processing 2 Processing 3 Processing 4 Processing 5 Processing 6 Processing 7 Processing 8 Processing 9 Processing 10 Processing done Done</strong>
以上是在Java 9中,我们如何实现Subscriber接口?的详细内容。更多信息请关注PHP中文网其他相关文章!