gpt4 book ai didi

java - 带有匿名线程的 Reactor Scheduler

转载 作者:行者123 更新时间:2023-12-02 01:42:23 25 4
gpt4 key购买 nike

我正在测试reactor的工作原理,创建了与reactor文档中可以找到的代码非常相似的代码。

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;

@SpringBootTest
@RunWith(SpringRunner.class)
public class ReactorApplicationTests {

@Test
public void publishOnThreadTest() {
Scheduler s = Schedulers.newParallel("parallel-scheduler", 4);

final Mono<String> mono = Mono.just("Publish on test: \n")
.map(msg -> msg + "before: " + Thread.currentThread() )
.publishOn(s)
.map(msg -> msg + "\nafter: " + Thread.currentThread());

new Thread(() -> mono.subscribe(System.out::println)).start();
}
}

我无法让它运行,我做错了什么?只要订阅它就可以了,但我想看看使用的线程并玩一下它。

最佳答案

您的测试程序不打印任何内容的原因是它退出得太早。它应该等到订阅者的方法被调用:

@Test
public void publishOnThreadTest() throws InterruptedException {
Scheduler s = Schedulers.newParallel("parallel-scheduler", 4);
CountDownLatch latch = new CountDownLatch(1);

final Mono<String> mono = Mono.just("Publish on test: \n")
.map(msg -> msg + "before: " + Thread.currentThread() )
.publishOn(s)
.map(msg -> msg + "\nafter: " + Thread.currentThread());

new Thread(() -> mono.subscribe((String str) ->{
System.out.println(str);
latch.countDown();
})).start();

latch.await();
}

关于java - 带有匿名线程的 Reactor Scheduler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54275155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com