接收可观察物

时间:2018-11-21 12:50:27

标签: java multithreading rx-java reactive-programming

这是我的代码:

  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线程没有退出并等待后台线程结束?该程序将继续运行,直到每个后台线程都在运行。

1 个答案:

答案 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之后立即退出。