我找不到使用 Mono.block() 和 Mono.subscribe() 的区别
对我来说,当使用这两种方法时,代码的行为完全相同。但它不应该。
对于 Mono.block() 我的期望是调用它的线程将阻塞并等待结果,但它在 Mono 的 map 方法中使用,并且基本上会自行解除阻塞。
我有以下使用 Mono.block() 的代码片段:
void doBlocking() {
final var myMono = Mono.just("test").map(elem -> {
System.out.printf("On thread: [%s] inside map\n",Thread.currentThread().getName());
return elem;
});
String value;
System.out.printf("On thread: [%s] before block\n",Thread.currentThread().getName());
value = myMono.block();
System.out.printf("On thread: [%s] after block\n",Thread.currentThread().getName());
System.out.println(value);
}
当我调用此代码时,我收到以下内容:
On thread: [main] before block
On thread: [main] inside map
On thread: [main] after block
test
根据我的理解 Mono.block() 是阻塞方法,所以我假设线程将像获取锁时一样被阻塞。相反,线程用于在Mono 的映射内部执行代码,这意味着它根本不会被阻塞。
对于Mono.subscribe()我希望调用 subscribe 的线程将继续而不等待结果,但它的行为与使用Mono.block()时完全相同
我有一个类似的片段,但现在使用订阅而不是块
void doSubscribing() {
final var myMono = Mono.just("test").map(elem -> {
System.out.printf("On thread: [%s] inside map\n",Thread.currentThread().getName());
return elem;
});
AtomicReference<String> value = new AtomicReference<>();
System.out.printf("On thread: [%s] before subscribe\n",Thread.currentThread().getName());
myMono.subscribe(value::set);
System.out.printf("On thread: [%s] after subscribe\n",Thread.currentThread().getName());
System.out.println(value);
}
当我再次调用此代码时,我得到相同的结果:
On thread: [main] before subscribe
On thread: [main] inside map
On thread: [main] after subscribe
test
我希望当我调用 subscribe 时,当前线程将继续工作,可能显示:
On thread: [main] after subscribe
null
就我而言,阻止和订阅的行为完全相同,那么真正的区别是什么?