ホームページ  >  記事  >  Java  >  Java 9 でパブリッシュ/サブスクライブ パターンを使用して Flow API を実装するにはどうすればよいですか?

Java 9 でパブリッシュ/サブスクライブ パターンを使用して Flow API を実装するにはどうすればよいですか?

WBOY
WBOY転載
2023-08-25 19:45:02986ブラウズ

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

Flow API (java.util.concurrent.Flow) は Java 9 で導入されました。 Publisher インターフェイスと SSubscriber インターフェイスが相互作用して必要なアクションを実行するさまざまな方法を理解するのに役立ちます。

フロー API は、パブリッシャー、サブスクライバー、サブスクリプション、および プロセッサ インターフェイスで構成されており、これらはリアクティブ フロー仕様に基づくことができます。

次の例では、パブリッシャー/サブスクライバー インターフェイスを使用してフロー 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[]) {
      <strong>Publisher<Integer></strong> publisherSync = new <strong>Publisher<Integer></strong>() {   <strong>// Create publisher</strong>
         <strong>@Override</strong>
         public void <strong>subscribe</strong>(Subscriber<? super Integer><!--? super Integer--> subscriber) {
            for(int i = 0; i < 10; i++) {
               System.out.println(Thread.currentThread().getName() + " | Publishing = " + i);
               subscriber.<strong>onNext</strong>(i);
            }
            subscriber.<strong>onComplete</strong>();
         }
      };
      <strong>Subscriber<Integer></strong> subscriberSync = new <strong>Subscriber<Integer></strong>() {   <strong>// Create subscriber</strong>
         <strong>@Override</strong>
         public void <strong>onSubscribe</strong>(Subscription subscription) {
         }
         <strong>@Override</strong>
         public void <strong>onNext</strong>(Integer item) {
            System.out.println(Thread.currentThread().getName() + " | Received = " + item);
            try {
               Thread.sleep(100);
            } catch(InterruptedException e) {
               e.printStackTrace();
            }
         }
         <strong>@Override</strong>
         public void <strong>onError</strong>(Throwable throwable) {
         }
         <strong>@Override</strong>
         public void <strong>onComplete()</strong> {
         }
      };
      publisherSync.<strong>subscribe</strong>(subscriberSync);
   }
}

出力

<strong>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</strong>

以上がJava 9 でパブリッシュ/サブスクライブ パターンを使用して Flow API を実装するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はtutorialspoint.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。