繁体   English   中英

RxJava 在并行处理时不会使用调度器中的所有线程

[英]RxJava does not use all the threads in a Scheduler while parallel processing

RxJava 任务提供了一个包含 20 个线程的调度程序。 它没有使用所有线程。

代码块

import io.reactivex.Flowable;
import io.reactivex.schedulers.Schedulers;

List<Integer> list = IntStream.range(1, 20).boxed().collect(Collectors.toList());
Iterable<Integer> iterable = Flowable.fromIterable(list)
    .parallel()          
    .runOn(Schedulers.from(Executors.newFixedThreadPool(20)))
    .map(i -> {
        System.out.println(Thread.currentThread().getName() + " - i = " + i);
        TimeUnit.SECONDS.sleep(i % 5);
        return i * i;
    })
    .sequential()
    .blockingIterable();
list = StreamSupport.stream(iterable.spliterator(), false)
        .collect(Collectors.toList());
System.out.println(list);

输出,仅使用 4 个线程。 调度程序包含 20 个线程。

pool-1-thread-1 - i = 1
pool-1-thread-5 - i = 2
pool-1-thread-4 - i = 4
pool-1-thread-3 - i = 3
pool-1-thread-1 - i = 5
pool-1-thread-1 - i = 9
pool-1-thread-5 - i = 6
pool-1-thread-5 - i = 10
pool-1-thread-5 - i = 14
pool-1-thread-3 - i = 7
pool-1-thread-4 - i = 8
pool-1-thread-1 - i = 13
pool-1-thread-3 - i = 11
pool-1-thread-3 - i = 15
pool-1-thread-3 - i = 19
pool-1-thread-4 - i = 12
pool-1-thread-5 - i = 18
pool-1-thread-1 - i = 17
pool-1-thread-4 - i = 16
[1, 25, 4, 36, 9, 100, 16, 81, 49, 121, 225, 196, 64, 169, 144, 256, 289, 324, 361]

因为来自文档的parallel()

创建多个“轨道”(等于 CPU 数量)

还有关于runOn文档:

请注意,rails 不会自己并行执行,需要应用 ParallelFlowable.runOn(Scheduler) 来指定每个 rail 将执行的调度程序。

所以你的实际并行度等于 CPU 的数量。 只需使用parallel(int parallelism)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM