这是我的代码:
public static void main(String[] args) {
Observable.just("747", "737", "777")
.flatMap(
a -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return Observable.just(a).subscribeOn(Schedulers.newThread());
})
.subscribe(p -> System.out.println("Received " + p + " on thread " + Thread.currentThread().getName()));
}
据我所知,可观察对象的每个项目都应在单独的线程中运行(这确实会发生),并将结果发送到完成工作的同一线程中(这也会发生)。但是我不明白的是,为什么main
线程没有退出并等待后台线程结束?该程序将继续运行,直到每个后台线程都在运行。
答案 0 :(得分:1)
如果查看线程转储,您会发现main
线程实际上停留在sleep
语句上。这就是为什么它不退出。
这是因为执行flatMap
运算符的是线程,所以它被卡住了。这也是为什么代码需要很长时间才能运行的原因。您可以通过在sleep
之前插入打印语句来轻松地对其进行验证:
try {
System.out.println(Thread.currentThread().getName() + " is sleeping");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
输出是这样的:
main is sleeping
main is sleeping
Received 747 on thread RxNewThreadScheduler-1
main is sleeping
Received 737 on thread RxNewThreadScheduler-2
Received 777 on thread RxNewThreadScheduler-3
我认为您打算写这样的东西:
System.out.println(Thread.currentThread().getName() + " is creating the observable");
Observable.just("747", "737", "777")
.flatMap(a ->
Observable.fromCallable(() -> {
try {
System.out.println(Thread.currentThread().getName() + " is sleeping");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return a;
}).subscribeOn(Schedulers.newThread())
).subscribe(p -> System.out.println("Received " + p + " on thread " + Thread.currentThread().getName()));
System.out.println(Thread.currentThread().getName() + " is going to exit");
输出:
main is creating the observable
main is going to exit
RxNewThreadScheduler-3 is sleeping
RxNewThreadScheduler-2 is sleeping
RxNewThreadScheduler-1 is sleeping
Received 777 on thread RxNewThreadScheduler-3
Received 747 on thread RxNewThreadScheduler-1
Received 737 on thread RxNewThreadScheduler-1
在此版本中,main
将在创建Observable之后立即退出。