我正在看documentation一种使用 Reactor 作为任务执行器的方法。我想提交一些任务,并行化它,然后像 ThreadService 一样等待它终止,示例如下:
final ExecutorService pool = Executors.newFixedThreadPool(10);
pool.submit(() -> {sleep(200);System.out.println(1);});
pool.submit(() -> System.out.println(2));
pool.submit(() -> System.out.println(3));
pool.submit(() -> System.out.println(4));
pool.submit(() -> System.out.println(5));
pool.submit(() -> System.out.println(6));
pool.submit(() -> System.out.println(7));
pool.submit(() -> System.out.println(8));
pool.submit(() -> System.out.println(9));
pool.submit(() -> System.out.println(10));
pool.awaitTermination(5, TimeUnit.SECONDS);
pool.shutdown();
我只是在将结果收集到列表时才得到这个
final List<Integer> result = Flux.range(1, 15)
.parallel()
.runOn(Schedulers.elastic())
.map(n -> {
// simulating heavy task
sleep((long) (Math.random() * 100));
return n;
})
.sequential()
.collectList().block();
System.out.println(result);
有更好的方法吗?
最佳答案
首先请记住,您的阻塞map
仅没问题,因为您在弹性Scheduler
中运行它(可能是parallel()
也是)。
如果你不关心结果并且想要在终止时阻塞,你可以使用.blockLast()
(它将返回最后计算的n
,但你可以忽略它。
如果您想在链上进一步组合,例如启动另一个进程,您可以链接任何风格的 then
,这将返回表示任务终止的 Mono
(删除数据事件)。
关于java - 使用Reactor作为任务执行器的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47353526/