项目反应堆:Flux.create()之后的subscribeOn()不一致地使用调度程序线程

时间:2018-10-23 17:26:50

标签: java spring multithreading project-reactor

当我运行下面的代码时,我希望看到两个订户都有自己的弹性线程。但是,他们并非始终如此。例如,在我的系统上,如果我取消注释thread.Sleep(100)行,则我的打印语句表明使用者正在主线程上接收其数据。如果不加评论,我将看到预期的输出:每个使用者都在自己的弹性线程上接收其数据。为什么我会看到这种不确定的行为?我如何滥用API?

    List<FluxSink<String>> holder = new ArrayList<>();
    ConnectableFlux<String> connect = Flux. 
           <String>create(holder::add).replay();
    connect.connect();
    Flux<String> flux = connect.subscribeOn(Schedulers.elastic());
    FluxSink<String> sink = holder.get(0);

    flux.subscribe(c -> {
       System.out.println(Thread.currentThread().getName() + ", " + 
         "consumer 1 says " + c);
    });

    flux.subscribe(c -> {
        System.out.println(Thread.currentThread().getName() + ", " + 
          "consumer 2 says " + c);
    });
    // When uncommented, subscribers receive on elastic threads; else,
    // on the main thread, as if I had chosen schedulers.immediate()
    //
    // Thread.sleep(100);
    sink.next("Hi!");

    sink.complete();

    Thread.sleep(1000);

    //output with Thread.sleep(100):
    // main, consumer 1 says Hi!
    // main, consumer 2 says Hi!
    //
    //output without Thread.sleep(100):
    // elastic-2, consumer 1 says Hi!
    // elastic-3, consumer 2 says Hi!

我想要实现的是一个热流,其中有多个订阅者,每个订阅者都在自己的线程上。

0 个答案:

没有答案