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中文網其他相關文章!