小编Cor*_*ral的帖子

如何在RxJava2中并行执行使用者?

我有一个关于RxJava2的问题.我想在固定线程池的不同线程中运行使用者以并行执行List结果.这是我的代码:

    List<String> letters = Lists.newArrayList("a","b","c","d","e","f","g");
    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(letters.size());
    Observable.fromIterable(letters).observeOn(Schedulers.from(fixedThreadPool)).forEach(new Consumer<String>() {
        @Override
        public void accept(String data) throws Exception {
            System.out.println(data + " forEach, thread is " + Thread.currentThread().getName());
        }
    });
Run Code Online (Sandbox Code Playgroud)

我得到的结果是:

a forEach, thread is pool-1-thread-1
b forEach, thread is pool-1-thread-1
c forEach, thread is pool-1-thread-1
d forEach, thread is pool-1-thread-1
e forEach, thread is pool-1-thread-1
f forEach, thread is pool-1-thread-1
g forEach, thread is pool-1-thread-1
Run Code Online (Sandbox Code Playgroud)

但实际上我想要的是这个结果,每个消费者并行执行不同的线程:

a forEach, thread is pool-1-thread-1
b forEach, thread is pool-1-thread-2
c forEach, …
Run Code Online (Sandbox Code Playgroud)

java multithreading rx-java rx-java2

3
推荐指数
1
解决办法
1057
查看次数

标签 统计

java ×1

multithreading ×1

rx-java ×1

rx-java2 ×1