我已經創建了一個固定的線程池來處理每300毫秒發送一個事件,並假定該進程需要1000毫秒。假設多線程將工作,但只有一個線程被重用。RxJava - 爲什麼執行者只使用一個線程
如果我設置的sleepTime小於300毫秒,處理線程改變,但是沒用。
問題:我能做些什麼來使它併發?爲什麼程序重用線程?
預先感謝您
public static void main(String[] args) throws InterruptedException {
long sleepTime = 1000;
ExecutorService e = Executors.newFixedThreadPool(3);
Observable.interval(300, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.computation())
.flatMap(new Func1<Long, Observable<Long>>() {
@Override
public Observable<Long> call(Long pT) {
return Observable.just(pT).subscribeOn(Schedulers.from(e));
}
})
.doOnNext(new Action1<Long>() {
@Override
public void call(Long pT) {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
})
.subscribe(new Action1<Long>() {
@Override
public void call(Long pT) {
System.out.println("i am " + pT + "in thread:" + Thread.currentThread().getName());
}
});
Thread.sleep(50000);
e.shutdownNow();
}
日誌
i am 0in thread:pool-1-thread-1
i am 1in thread:pool-1-thread-1
i am 2in thread:pool-1-thread-1
i am 3in thread:pool-1-thread-1
i am 4in thread:pool-1-thread-1
i am 5in thread:pool-1-thread-1
i am 6in thread:pool-1-thread-1
i am 7in thread:pool-1-thread-1
i am 8in thread:pool-1-thread-1
i am 9in thread:pool-1-thread-1
i am 10in thread:pool-1-thread-1
i am 11in thread:pool-1-thread-1
請注意:您可以使用jvisualvm來更加可靠地計算出進度計劃和使用哪些線程:http://docs.oracle.com/javase/6/docs/technotes/tools/ share/jvisualvm.html –
@ReutSharabani在eclipse Debug視圖中,我可以看到生成的線程,但程序只重用一個線程。 – Rockman12352