
本文的合集已經(jīng)編著成書,高級(jí)Android開發(fā)強(qiáng)化實(shí)戰(zhàn),歡迎各位讀友的建議和指導(dǎo)。在京東即可購買:https://item.jd.com/12385680.html

隨著手機(jī)的發(fā)展, 其性能已經(jīng)與電腦越來越接近, 也會(huì)有一些復(fù)雜耗時(shí)的并行任務(wù)需要處理, 對(duì)于異步與并行, RxAndroid是我們的最佳選擇. 那么讓我來使用實(shí)例介紹一下吧.
在計(jì)算調(diào)度器Schedulers.computation()中, 可以并行處理任務(wù), 核數(shù)是Rx根據(jù)手機(jī)CPU定制的, 在我的華為P8手機(jī)(8核)中, 使用的是8個(gè)線程. 但是根據(jù)Java線程的最佳配置而言, 8核最佳是9個(gè)線程, 即線程數(shù)等于核數(shù)+1.
本文源碼的GitHub下載地址
配置
RxAndroid+ButterKnife, 我是ButterKnife的粉絲.
compile 'com.jakewharton:butterknife:7.0.1'
compile 'io.reactivex:rxjava:1.1.0'
compile 'io.reactivex:rxandroid:1.1.0'
計(jì)算線程
MAX是并行執(zhí)行的任務(wù)數(shù). 使用flatMap逐個(gè)分發(fā)到計(jì)算線程computation中, 執(zhí)行耗時(shí)任務(wù)intenseCalculation.
// 計(jì)算線程并行, 8核
public void computePara(View view) {
mTvComputeValue.setText("計(jì)算中");
Observable.range(MIN, MAX)
.flatMap(i -> Observable.just(i)
.subscribeOn(Schedulers.computation()) // 使用Rx的計(jì)算線程
.map(this::intenseCalculation)
)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::computeTag);
}
使用intenseCalculation模擬耗時(shí)任務(wù).
// 模擬耗時(shí)計(jì)算
private int intenseCalculation(int i) {
try {
tag("Calculating " + i + " on " + Thread.currentThread().getName());
Thread.sleep(randInt(100, 500));
return i;
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
最大線程
最大線程數(shù) = CPU核數(shù) + 1
由于CPU的核數(shù)是8, 因此我們選擇9個(gè)線程. 創(chuàng)建執(zhí)行器executor, 使用執(zhí)行器創(chuàng)建Rx的調(diào)度器Scheduler, 處理異步任務(wù).
// 定制線程并行, 9核
public void customPara(View view) {
int threadCt = Runtime.getRuntime().availableProcessors() + 1;
mTvCustomValue.setText(String.valueOf("計(jì)算中(" + threadCt + "線程)"));
ExecutorService executor = Executors.newFixedThreadPool(threadCt);
Scheduler scheduler = Schedulers.from(executor);
Observable.range(MIN, MAX)
.flatMap(i -> Observable.just(i)
.subscribeOn(scheduler)
.map(this::intenseCalculation)
).observeOn(AndroidSchedulers.mainThread())
.subscribe(this::customTag);
}
高版本計(jì)算CPU核數(shù)的方式.
Runtime.getRuntime().availableProcessors()
低版本, 參考.
private int getNumCoresOldPhones() {
//Private Class to display only CPU devices in the directory listing
class CpuFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
//Check if filename is "cpu", followed by a single digit number
if (Pattern.matches("cpu[0-9]+", pathname.getName())) {
return true;
}
return false;
}
}
try {
//Get directory containing CPU info
File dir = new File("/sys/devices/system/cpu/");
//Filter to only list the devices we care about
File[] files = dir.listFiles(new CpuFilter());
//Return the number of cores (virtual CPU devices)
return files.length;
} catch (Exception e) {
//Default to return 1 core
return 1;
}
}
循環(huán)賽模式
循環(huán)賽模式(Round-Robin)是把數(shù)據(jù)分組, 按線程數(shù)分組, 每組9個(gè), 一起發(fā)送處理. 這樣做, 可以減少Observable的創(chuàng)建, 節(jié)省系統(tǒng)資源, 但是會(huì)增加處理時(shí)間, 是空間和時(shí)間的綜合考慮.
int threadCt = Runtime.getRuntime().availableProcessors() + 1;
mTvGroupedValue.setText(String.valueOf("計(jì)算中(" + threadCt + "線程)"));
ExecutorService executor = Executors.newFixedThreadPool(threadCt);
Scheduler scheduler = Schedulers.from(executor);
final AtomicInteger batch = new AtomicInteger(0);
Observable.range(MIN, MAX)
.groupBy(i -> batch.getAndIncrement() % threadCt)
.flatMap(g -> g.observeOn(scheduler).map(this::intenseCalculation))
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::groupedTag);
這是Compute \ Max \ Group三種效果的時(shí)間對(duì)比, 可以發(fā)現(xiàn)Max的時(shí)間最優(yōu), 因?yàn)楸菴ompute多一個(gè)線程, 但是Group會(huì)更加節(jié)省資源一些. 根據(jù)所執(zhí)行的并行任務(wù)使用Rx吧.
效果

OK, that's all! Enjoy it!