publishOn
和parallel
有什么区别?据我了解,publishOn
通过使用几个线程执行操作符链来影响操作符链的进一步处理。但是 parallel
似乎和它的工作原理完全一样。默认情况下,它会创建一个大小为 == #cores 的线程池,并以相同的方式处理运算符的链。还是我遗漏了一些微妙之处?
Schedulers部分状态:
[publishOn] takes signals from upstream and replays them downstream while executing the callback on a worker from the associated Scheduler
和,
a fixed pool of workers that is tuned for parallel work (Schedulers.parallel()). It creates as many workers as you have CPU cores.
因此 publishOn(Schedulers.parallel()
创建尽可能多的线程是核心,并与这些工作人员一起执行链中的后续 operators
。
然后 Parralel部分状态:
you can use the parallel() operator on any Flux. By itself, this method does not parallelize the work. Rather, it divides the workload into "rails" (by default, as many rails as there are CPU cores).
In order to tell the resulting ParallelFlux where to execute each rail (and, by extension, to execute rails in parallel) you have to use runOn(Scheduler). Note that there is a recommended dedicated Scheduler for parallel work: Schedulers.parallel().
下面两个例子:
Flux.range(1, 10)
.parallel(2)
.runOn(Schedulers.parallel())
.subscribe(i -> System.out.println(Thread.currentThread().getName() + " -> " + i));
和
Flux.range(1, 10)
.publishOn(Schedulers.parallel())
.subscribe(i -> System.out.println(Thread.currentThread().getName() + " -> " + i));
假设计算机有两个核心,以上两个例子是等价的吗?
最佳答案
我想我有这个问题的答案。
经过一些测试后,我发现 publishOn(Schedulers.parallel()
将在单独的线程上按顺序处理您的 Flux
。
但是,
使用 parallel().runOn(Schedulers.parallel())
会将您的 Flux
拆分为您拥有的内核数量,并且每个新的 Flux
将被并行处理。因此,每个新 Fluxes
中的数据可能会按顺序处理,但 Fluxes
一起将是并行处理。
关于java - publishOn 和并行的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45957607/