【发布时间】:2015-12-30 05:50:43
【问题描述】:
我创建了一个固定线程池来处理每 300 毫秒发出的事件,并假设该过程需要 1000 毫秒。假设多线程可以工作,但只有一个线程被重用。
如果我将 sleepTime 设置为小于 300ms,则处理线程会改变,但那是无用的。
问题:我可以做些什么来使它并发?为什么程序要复用线程?
提前谢谢你
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 更可靠地了解在调度方面发生了什么以及使用了哪些线程:docs.oracle.com/javase/6/docs/technotes/tools/share/…
-
@ReutSharabani 在 Eclipse Debug 视图中,我可以看到线程已经生成,但是程序只重用了一个线程。
标签: java multithreading rx-java reactivex rx-javafx