這是我的示例代碼RxJava:使用SubscribeOn使得程序退出沒有完成
Observable.range(1,5)
.subscribeOn(Schedulers.computation())
.map(Observables05::doSomething)
.subscribe(System.out::println, Throwable::printStackTrace,() -> System.out.println("done"));
我DoSomething的方法是,
public static int doSomething(int i) {
try {
System.out.println("Processing " + i +
" on Thread -- " + Thread.currentThread().getName());
Thread.sleep(500);
return i;
} catch (InterruptedException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
僅使用我的主線程的代碼直接退出程序。但是,如果在此之後使用Thread.sleep(3000)
,那麼程序在睡眠時間結束時退出之前會正常工作。
這是預期的行爲,爲什麼?如何在不使用Thread.sleep
的情況下運行此代碼?
任何方式來實現這一點沒有'Thread.sleep'? – Dripto