首頁 > Java > java教程 > 主體

我們如何在Java 9中使用發布-訂閱模式來實作Flow API呢?

WBOY
發布: 2023-08-25 19:45:02
轉載
1023 人瀏覽過

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

Flow API (java.util.concurrent.Flow) 已在 Java 9 中引入。它有助於了解發布商S訂閱者介面互動以執行所需操作的不同方式。

Flow API 由發布者、訂閱者、訂閱處理器介面組成,這些介面可以基於反應式串流規格。

在下面的範例中,我們可以使用發布者-訂閱者介面來實作 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[]) {
      <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中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!