我创建了一个固定线程池来处理每 300 毫秒发出的事件,并假设该过程需要 1000 毫秒。假设多线程可以工作,但只有一个线程被重用。
如果我将 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