具有匿名线程的Reactor Scheduler

时间:2019-01-20 09:35:48

标签: java multithreading project-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();
  }
}

我无法使其运行,我在做什么错?只需订阅,它可以工作,但我想看看使用的线程并对其进行处理。

1 个答案:

答案 0 :(得分:2)

您的测试程序什么也不打印的原因是因为它退出太早。它应该等到子结构的方法被调用:

@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();
}