为什么两秒后控制台没有信息输出---Rxjava [英] Why is there no information output from the console after two seconds --- Rxjava
本文介绍了为什么两秒后控制台没有信息输出---Rxjava的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public class RxJavaTest {
public static void main(String[] args) {
Observable.timer(2, TimeUnit.SECONDS).subscribe(new Consumer<Long>() {
@Override
public void accept(Long aLong) throws Exception {
System.out.println("timer: accept " + aLong);
}
});
}
}
为什么两秒后控制台没有信息输出?
Why is there no information output from the console after two seconds?
推荐答案
默认情况下,timer
操作符在不同的线程(在计算线程池中)和你的 main
中执行code> 线程在调用 subscribe 并关闭 VM 后立即退出.
By default the timer
operator is executed in a different Thread (in the computation thread pool) and your main
thread is exited just after calling the subscribe and shutdowns the VM.
对此您有不同的解决方案.
Yo have different solutions for this.
- 在
subscribe
之后添加一个Thread.sleep(value > 2000)
- 调用
blockingSubscribe
而不是subscribe
.当前线程(main)阻塞,直到上游终止 - 将时间表更改为蹦床:
- Add a
Thread.sleep(value > 2000)
after yoursubscribe
- Call
blockingSubscribe
instead ofsubscribe
. The current thread (main) blocks until the upstream terminates - Change the time scheduler to trampoline :
Observable.timer(2, TimeUnit.SECONDS, Schedulers.trampoline())
来自文档
默认实现的 {@linkScheduler#scheduleDirect(Runnable)} 方法在没有任何排队的当前线程和定时重载使用也阻止睡眠.
The default implementation's {@link Scheduler#scheduleDirect(Runnable)} methods execute the tasks on the current thread without any queueing and the timed overloads use blocking sleep as well.
这篇关于为什么两秒后控制台没有信息输出---Rxjava的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文