![](/img/trans.png)
[英]Why doesn't a simple Swing application terminate when a window is shown?
[英]Why doesn't my RxJava timer application terminate?
我有一個使用RxJava 2的簡單應用程序:
public static void main(final String[] args) {
final Scheduler scheduler = Schedulers.from(Executors.newCachedThreadPool());
final Observable<String> ticker = Observable.interval(1L, TimeUnit.SECONDS)
.take(10)
.subscribeOn(scheduler)
.map(x -> x + "s");
ticker.subscribe(x -> {
System.out.println(x);
});
}
它將正確打印計時器10次:
0s
1s
2s
3s
4s
5s
6s
7s
8s
9s
但是,應用程序不會在9s
之后終止。 似乎有一些線程使它保持活動狀態。
我應如何實現此功能,以便在ticker
完成后終止應用程序?
該問題與RxJava
,但與JVM規范的Executors.newCachedThreadPool()
無關,在所有非守護程序線程完成執行之前,控制台應用程序不會退出。 (或顯式調用System.exit()
)。
現在, newCachedThreadPool
執行程序將線程保留在緩存中以備將來使用,並且僅在無使用60秒后才會關閉線程(請參閱文檔),所以這里發生的是RxJava使用了該緩存中的線程,然后發出了所有項目,您需要等待60秒才能退出該應用(Juat運行它並等待)。
順便說一句, interval()
默認在computation
Scheduler
上起作用,您可以使用重載來覆蓋它,該重載也將Scheduler
作為參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.