Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么这种流量不是';t在多个线程中执行?_Java_Reactor - Fatal编程技术网

Java 为什么这种流量不是';t在多个线程中执行?

Java 为什么这种流量不是';t在多个线程中执行?,java,reactor,Java,Reactor,我举了以下例子: Flux.just(1,2,3,4,5,6,7,8) .flatMap(integer -> { System.out.println("val:" + integer + ", thread:" + Thread.currentThread().getId()); return Mono.just(integer); }, 5)

我举了以下例子:

Flux.just(1,2,3,4,5,6,7,8)
    .flatMap(integer -> {
                 System.out.println("val:" + integer + ", thread:" + Thread.currentThread().getId()); 
                 return Mono.just(integer);
             }, 5)
    .repeat()
    .subscribeOn(Schedulers.parallel())
    .subscribe();
日志如下:

val:4, thread:14
val:5, thread:14
val:6, thread:14
val:7, thread:14
val:8, thread:14
val:1, thread:14
val:2, thread:14
val:3, thread:14

为什么到处都是同一根线??如何修改示例以使其在多个线程中执行?

您需要使用
并行操作,如下所示:

Flux.just(1,2,3,4,5,6,7,8)
    .parallel(2) // mention number of threads
    .runOn(Schedulers.parallel())
    .map(integer -> {
             System.out.println("val:" + integer + ", thread:" + Thread.currentThread().getId()); 
             return integer;
        })   
    .subscribe();

如果希望每个重复的通量位于不同的线程上,可以在前面移动
publishOn
,如下所示:

Flux.just(1,2,3,4,5,6,7,8)
.publishOn(Schedulers.parallel())//{
System.out.println(“val:+integer+”,线程:+thread.currentThread().getId());
返回Mono.just(整数);
}, 5)
.重复
.subscribe();
现在的输出是这样的:

val:1, thread:20
val:2, thread:20
val:3, thread:20
val:4, thread:20
val:5, thread:20
val:6, thread:20
val:7, thread:20
val:8, thread:20
val:1, thread:13
val:2, thread:13
val:3, thread:13
val:4, thread:13
val:5, thread:13
val:6, thread:13
val:7, thread:13
val:8, thread:13
如果希望每个整数位于不同的线程中,可以执行以下操作:

Flux.just(1,2,3,4,5,6,7,8)
.publishOn(Schedulers.parallel())//{
返回Mono.fromCallable(()->{
System.out.println(“val:+integer+”,线程:+thread.currentThread().getId());
返回整数;
}).publishOn(Schedulers.parallel())//
val:3, thread:16
val:2, thread:15
val:7, thread:20
val:8, thread:13
val:5, thread:18
val:6, thread:19
val:3, thread:17
val:5, thread:19
val:6, thread:20
val:1, thread:15
val:8, thread:14
val:4, thread:18
val:7, thread:13