首頁 >Java >java教程 >在Java 9中,我們如何實作Subscriber介面?

在Java 9中,我們如何實作Subscriber介面?

WBOY
WBOY轉載
2023-09-04 13:33:07804瀏覽

在Java 9中,我们如何实现Subscriber接口?

Java 9 透過引入一些介面來支援建立反應式流PublisherSubscriberSubscription與實作Publisher 介面的SubmissionPublisher 類別。每個介面可以根據反應式流的原則扮演不同的角色。

我們可以使用Subscriber 介面訂閱由publisher發布的資料。我們需要實作Subscriber 介面並為抽象方法提供實作。

Flow.Subscriber介面的方法:

  • onComplete():當Publisher物件完成其角色時呼叫此方法。
  • onError():當Publisher出現問題並通知Subscriber時呼叫此方法。
  • onNext():當Publisher有新資訊要通知所有Subscribers時呼叫此方法。
  • onSubscribe():當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中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除