java - 带有匿名线程的 Reactor Scheduler

标签 java multithreading project-reactor reactor

我正在测试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/

相关文章:

java - 如何使用自定义协议(protocol)测试网络应用程序?

C++多线程Windows GUI(访问表单)

cURL 由于线程(或套接字?)过多而返回错误 [C]

java - Mono#then 和 Mono#and 之间的区别?

java - JDatePicker 没有出现在 JFrame 上

java - 枚举 values() 方法效率

c++ - 在多线程 HTTP 服务器中发送后如何干净地关闭套接字?

project-reactor - Spring Mongo 响应式(Reactive)处理数据库保存错误

project-reactor - 为什么Thread.sleep()会触发对Flux.interval()的订阅?

java - 如何在不知道字符串格式的情况下将字符串转换为日期?