我正在学习使用项目 react 器进行响应式编程。
我有以下测试用例:
@Test
public void createAFlux_just() {
Flux<String> fruitFlux = Flux.just("apple", "orange");
fruitFlux.subscribe(f -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(f);
});
System.out.println("hello main thread");
}
通过执行测试,主线程似乎卡住了5秒。
我希望订阅的消费者应该在自己的线程中异步运行,也就是说,订阅调用应该立即返回到主线程,因此hello主线程
应该立即打印。
最佳答案
主线程被卡住,因为订阅发生在main
上线。如果您希望它异步运行,则需要在 main
以外的线程上进行订阅。 。您可以这样做:
@Test
public void createAFlux_just() {
Flux<String> fruitFlux = Flux.just("apple", "orange");
fruitFlux.subscribeOn(Schedulers.parallel()).subscribe(f -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(f);
});
System.out.println("hello main thread");
}
注意:我使用了parallel
线程池。您可以使用任何您喜欢的游泳池。 Reactor 的管道默认在调用线程上执行(与默认在 CompletableFuture<T>
池中运行的 ForkJoin
不同)。
关于java - 响应式(Reactive)编程(Reactor): Why main thread is stuck?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64097135/