为什么这个通量不在单线程中执行?

lsmepo6l  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(346)

我的功能是这样执行的:

@EventListener(classes = {ApplicationReadyEvent.class})
    public void executeSendingNotificationToServer() {
        serverNotificationService.trySendNotification(msgCount, msgTime)
                .delaySubscription(Duration.ofMillis(notificationServerProperties.getExecutorDelay()))
                .repeat()
                .subscribeOn(Schedulers.single())
                .subscribe();
    }

方法trysendnotification以某种方式执行(这无关紧要)。
为什么它不在单线程中执行?我显式地设置schedulers.single(),文档中声明它将在一个线程中执行。
相反,我可以观察到创建了多个线程(我在方法中输入线程名称,然后它打印不同的名称)

j7dteeu8

j7dteeu81#

你应该把车开走 subscribeOn 在延迟之前。
下面是一个示例,使用代码但打印线程编号:

Mono.fromCallable(() -> {
    System.out.println("Thread = " + Thread.currentThread().getId());
    return "hello world";
})
.delaySubscription(Duration.ofMillis(500))
.repeat()
.subscribeOn(Schedulers.single())
.subscribe();

正如您所说,输出显示它是在不同的线程中执行的:

Thread = 14
Thread = 15
Thread = 16
Thread = 17
Thread = 18
Thread = 19
Thread = 20
Thread = 21
Thread = 14

现在,如果我像这样移动它:

Mono.fromCallable(() -> {
    System.out.println("Thread = " + Thread.currentThread().getId());
    return "hello world";
})
.subscribeOn(Schedulers.single()) // <- BEFORE
.delaySubscription(Duration.ofMillis(500))
.repeat()
.subscribe();

输出变为:

Thread = 14
Thread = 14
Thread = 14
Thread = 14
Thread = 14
Thread = 14
Thread = 14
Thread = 14
Thread = 14

相关问题