首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >反应器3发射器/用户并联

反应器3发射器/用户并联
EN

Stack Overflow用户
提问于 2019-02-21 16:30:41
回答 1查看 89关注 0票数 2

我是响应式编程的新手,有很多问题。我认为这并不是缺乏示例或文档,而是我的理解是错误的。

我在试着模仿慢速用户;

以下是代码示例

代码语言:javascript
复制
Flux.create(sink -> {
    int i = 0;
    while (true) {
        try {
            System.out.println("Sleep for " + MILLIS);
            Thread.sleep(MILLIS);
            int it = i++;
            System.out.println("Back to work, iterator " + it);
            sink.next(it);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}).subscribeOn(Schedulers.elastic())
.subscribe(x -> {
    try {
        System.out.println("Value: " + x + ", Thread: " + Thread.currentThread().toString());
        Thread.sleep(MILLIS + 4000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
});

系统输出为

代码语言:javascript
复制
Sleep for 1000
Back to work, iterator 0
Value: 0, Thread: Thread[elastic-2,5,main]
Sleep for 1000
Back to work, iterator 1
Value: 1, Thread: Thread[elastic-2,5,main]
Sleep for 1000
Back to work, iterator 2
Value: 2, Thread: Thread[elastic-2,5,main]

我想如果订阅者很慢,我应该会看到更多的线程,因为Schedulers.elastic()

我也试着让publishOn()看起来像是异步的,但是仍然不能处理几个线程的结果。

感谢您的评论和回答。

EN

回答 1

Stack Overflow用户

发布于 2019-02-21 18:36:02

如果你想让它在不同的线程中运行,你需要像这样使用.parallel(),它将会在不同的线程中运行

代码语言:javascript
复制
Flux.create(sink -> {
        int i = 0;
        while (true) {
            try {
                System.out.println("Sleep for " + MILLIS);
                Thread.sleep(100);
                int it = i++;
                System.out.println("Back to work, iterator " + it);
                sink.next("a");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    })

            .parallel()
            .runOn(Schedulers.elastic())

            .subscribe(x -> {
                try {
                    System.out.println("Value: " + x + ", Thread: " + Thread.currentThread().toString());
                    Thread.sleep(100 + 4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            })
    ;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54802472

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档