我已经创建了一个固定的线程池来处理每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