跳转到主内容
新派编程网 - 新潮编程理念,全新技术课堂!

我们如何在Java 9中使用发布-订阅模式来实现Flow API呢?

Flow API (java.util.concurrent.Flow) 已在 Java 9 中引入。它有助于了解 发布商 和 S 订阅者 界面交互以执行所需操作的不同方式。 Flow AP I 由 发布者、订阅者、订阅 和 处理器 接口组成,这些接口可以基于反应式流规范。 在下面的示例中,我们可以使用发布者-订阅者接口来实现 Flow API。 示例
import java.util.concurrent.Flow.Publisher; import java.util.concurrent.Flow.Subscriber; import java.util.concurrent.Flow.Subscription; public class FlowAPITest { public static void main(String args[]) { Publisher publisherSync = new Publisher() { // Create publisher @Override public void subscribe(Subscriber subscriber) { for(int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName() + " | Publishing = " + i); subscriber.onNext(i); } subscriber.onComplete(); } }; Subscriber subscriberSync = new Subscriber() { // Create subscriber @Override public void onSubscribe(Subscription subscription) { } @Override public void onNext(Integer item) { System.out.println(Thread.currentThread().getName() + " | Received = " + item); try { Thread.sleep(100); } catch(InterruptedException e) { e.printStackTrace(); } } @Override public void onError(Throwable throwable) { } @Override public void onComplete() { } }; publisherSync.subscribe(subscriberSync); } }
输出
main | Publishing = 0 main | Received = 0 main | Publishing = 1 main | Received = 1 main | Publishing = 2 main | Received = 2 main | Publishing = 3 main | Received = 3 main | Publishing = 4 main | Received = 4 main | Publishing = 5 main | Received = 5 main | Publishing = 6 main | Received = 6 main | Publishing = 7 main | Received = 7 main | Publishing = 8 main | Received = 8 main | Publishing = 9 main | Received = 9

相关文章