谁能看看下面的代码,让我知道为什么这是不同的行为:
package com.example.rxjava;
import rx.Observable;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
public class MyRxJava {
public static void main(String[] args) {
System.out.println("getting sum ... by thread: " +
Thread.currentThread().getId());
// observeOnNewThread();
subOnNewThread();
independentProcess();
}
private static void observeOnNewThread() {
Observable.create(new CountObservable(100)).observeOn(Schedulers.newThread()).subscribe(new Action1<Integer>() {
@Override
public void call(Integer a) {
System.out.println("processing dependent process " + a + " ..... by thread: "+ Thread.currentThread().getId());
}
});
}
private static void subOnNewThread() {
Observable.create(new CountObservable(100)).subscribeOn(Schedulers.newThread()).subscribe(new Action1<Integer>() {
@Override
public void call(Integer a) {
System.out.println("processing dependent process " + a + " ..... by thread: " + Thread.currentThread().getId());
}
});
}
private static void independentProcess() {
System.out.println("precessing something else .... by thread: "+ Thread.currentThread().getId());
}
}
package com.example.rxjava;
import rx.Observable;
import rx.Subscriber;
public class CountObservable implements Observable.OnSubscribe<Integer> {
private int value;
public CountObservable(int value) {
this.value = value;
}
@Override
public void call(Subscriber<? super Integer> subscriber) {
System.out.println("calculating sum .... by thread: "+ Thread.currentThread().getId());
int tot = 0;
for (int k = 0; k<=value; k++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
tot+=k;
}
subscriber.onNext(tot);
subscriber.onCompleted();
}
}
有时会打印
getting sum ... by thread: 1
precessing something else .... by thread: 1
有时
getting sum ... by thread: 1
precessing something else .... by thread: 1
calculating sum .... by thread: 11
不管怎样,它不会打印
里面的信息@Override
public void call(Integer a) { ... }
方法当我运行observeOnNewThread()
方法时,它工作,但我想在不同的线程中计算总和
RxJava调度器在守护线程上运行,您的main方法在它们有机会运行到完成之前就完成了。您必须以某种方式等待它们:通过在main中休眠,通过使用toBlocking().forEach()
或其他toBlocking()
方法。