项目反应堆:调度程序#并行和调度程序#弹性用途

时间:2018-07-25 20:45:59

标签: java multithreading project-reactor

我正在学习Schedulers factory的地方学习Project Reactor

我尝试了以下代码:

    ExecutorService executorService = Executors.newFixedThreadPool(10);
    Flux.range(1,4)
                    .map(i -> {
                        logger.info(i +" [MAP] " + Thread.currentThread().getName());
                        return 10 / i;
                    })
                    .publishOn(Schedulers.fromExecutorService(executorService)) // .publishOn(Schedulers.parallel())
                    .subscribe(
                            n -> {
                                logger.info("START "+((Long)(System.currentTimeMillis() % 10000000L)).toString());
                                try {
                                    Thread.sleep(100);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                logger.info(n.toString());
                                logger.info("END "+((Long)(System.currentTimeMillis() % 10000000L)).toString());
                            }
                    );
        executorService.shutdown();

此代码也曾与Schedulers.parallel()Schedulers.elastic()一起尝试过。另外,尝试使用subscribeOn()运算符来查看类似结果。

日志为:

02:07:30.142 [main] INFO  - 1 [MAP] main
02:07:30.143 [main] INFO  - 2 [MAP] main
02:07:30.143 [main] INFO  - 3 [MAP] main
02:07:30.143 [main] INFO  - 4 [MAP] main
02:07:30.143 [pool-1-thread-2] INFO  - START 1050143
02:07:30.247 [pool-1-thread-2] INFO  - 10
02:07:30.247 [pool-1-thread-2] INFO  - END 1050247
02:07:30.247 [pool-1-thread-2] INFO  - START 1050247
02:07:30.350 [pool-1-thread-2] INFO  - 5
02:07:30.350 [pool-1-thread-2] INFO  - END 1050350
02:07:30.350 [pool-1-thread-2] INFO  - START 1050350
02:07:30.455 [pool-1-thread-2] INFO  - 3
02:07:30.455 [pool-1-thread-2] INFO  - END 1050455
02:07:30.455 [pool-1-thread-2] INFO  - START 1050455
02:07:30.557 [pool-1-thread-2] INFO  - 2
02:07:30.558 [pool-1-thread-2] INFO  - END 1050558

由于Flux的元素是按顺序排序和操作的(从上面的日志中可以明显看出),因此一个元素的operator(或operator chain)具有多个线程没有道理。我确信我是在误解Schedulers还是在我的基本理解上缺乏某些地方。有人可以指出我正确的方向吗?

我了解Schedulers进行处理asynchronous并释放main线程的目的。但是,为什么一次要在一个元素上进行操作时,有人想给operator(s)分配多个线程。

仅当我们处理flatMap operator时才有意义吗?

0 个答案:

没有答案