3
我有一個關於RxJava2的問題。我想在固定線程池的不同線程中運行消費者以並行執行List結果。這裏是我的代碼:如何在RxJava2中並行執行消費者?
List<String> letters = Lists.newArrayList("a","b","c","d","e","f","g");
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(letters.size());
Observable.fromIterable(letters).observeOn(Schedulers.from(fixedThreadPool)).forEach(new Consumer<String>() {
@Override
public void accept(String data) throws Exception {
System.out.println(data + " forEach, thread is " + Thread.currentThread().getName());
}
});
我得到的結果是:
a forEach, thread is pool-1-thread-1
b forEach, thread is pool-1-thread-1
c forEach, thread is pool-1-thread-1
d forEach, thread is pool-1-thread-1
e forEach, thread is pool-1-thread-1
f forEach, thread is pool-1-thread-1
g forEach, thread is pool-1-thread-1
但實際上我想是這樣的結果,每個並行consumor執行在不同的線程:
a forEach, thread is pool-1-thread-1
b forEach, thread is pool-1-thread-2
c forEach, thread is pool-1-thread-3
d forEach, thread is pool-1-thread-4
e forEach, thread is pool-1-thread-5
f forEach, thread is pool-1-thread-6
g forEach, thread is pool-1-thread-7
能有人告訴我如何讓它發生?
不要做'.toFlowable(BackpressureStrategy.MISSING)'和'平行()'!另外如果你有一個迭代器,爲什麼不使用'Flowable.fromIterable'並且你可以免費得到背壓? – akarnokd
採取@akarnokd點。將改變代碼片段 – Zapodot