흐름 API (java.util.concurrent.Flow)가 자바 9에 도입되었습니다. . 게시자 가 및 S 가입자 인터페이스는 원하는 작업을 수행하기 위해 상호 작용합니다.
흐름 AP 저는 게시자, 구독자, 구독으로 구성되어 있습니다. 및 프로세서 반응 스트림 사양을 기반으로 할 수 있는 인터페이스.
아래 예에서는 게시자-구독자 인터페이스를 사용하여 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<Integer> publisherSync = new Publisher<Integer>() { // Create publisher
@Override
public void subscribe(Subscriber<? super Integer> subscriber) {
for(int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " | Publishing = " + i);
subscriber.onNext(i);
}
subscriber.onComplete();
}
};
Subscriber<Integer> subscriberSync = new Subscriber<Integer>() { // 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