RxJava调度程序始终与sleep一起工作在同一个线程中

时间:2017-06-01 13:06:53

标签: java multithreading rx-java reactive-programming rx-java2

我试图在不同的线程上运行每个计算,但无论我使用它的Scheduler总是在单线程上运行。

PublishProcessor processor = PublishProcessor.create();

    processor
        .doOnNext(i ->System.out.println(i.toString()+" emitted on "+Thread.currentThread().getId()))
        .observeOn(Schedulers.newThread()).subscribe(i -> {
            System.out.println(i.toString()+" received on "+Thread.currentThread().getId());
            Thread.currentThread().sleep(5000);
        });
    processor.onNext(2);
    processor.onNext(3);
    processor.onNext(4);
    processor.onNext(5);
    processor.onNext(6);


    while (true) {}

输出结果为:

2 emitted on 1
3 emitted on 1
4 emitted on 1
5 emitted on 1
6 emitted on 1
2 received on 13
3 received on 13
4 received on 13
5 received on 13
6 received on 13

线程13仅在休眠后处理下一个值,但在这种情况下我想要几个单独的休眠线程。 有人可以解释我做错了吗?

1 个答案:

答案 0 :(得分:1)

.observeOn(...)通过更改为另一个线程的项目流来生效,但它始终是相同的线程。

如果您想为每个项目创建一个新线程

processor
    .doOnNext(i ->System.out.println(i.toString()+" emitted on "+Thread.currentThread().getId()))
    .flatMap(item -> Observable.just(item)
                         .subscribeOn(Schedulers.newThread()))    // make every item change to a new thread
    .subscribe(i -> {
        System.out.println(i.toString()+" received on "+Thread.currentThread().getId());
        Thread.currentThread().sleep(5000);
    });