多任务同时进行
问题:如果有一个对数据进行权限检查的操作,可能有1万条、10万条等等,只写一个任务执行它会花费很多时间,这时可以考虑分成多个任务把数据分成多段同时进行?
代码如下:
public abstract class ParallelTask {
private final static String TAG = "ParallelTask";
public ParallelTask() {
}
public void preExecute(Object... args) {
}
public abstract void async1(); //必须实现
public void async2() {
}
public void async3() {
}
public void async4() {
}
public void async5() {
}
public void async6() {
}
public void async7() {
}
public void async8() {
}
public void onAllExecute() {
}
public void onUICompleted() { //全部任务执行完成后会执行该方法
}
private Observable uiObs;
/**
* 执行并行任务,结束后切换到UI线程
*/
final public void execute(Object...args) {
preExecute(args);
//最外层,执行UI线程
uiObs = Observable.just(null).subscribeOn(AndroidSchedulers.mainThread());
List<String> methods = getOverrideMethods();
int size = methods.size();
String[] ms = methods.toArray(new String[size]);
getParallelObservable(ms)
.observeOn(Schedulers.immediate())
.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
onAllExecute();
executeOnUICompleted();
}
@Override
public void onError(Throwable e) {
Log.e(TAG, "ParallelTask onError()", e);
}
@Override
public void onNext(String string) {
}
});
}
/**
* 最后切换到UI线程执行
*/
private void executeOnUICompleted(){
if(uiObs != null){
uiObs.subscribe(new Action1() {
@Override
public void call(Object o) {
onUICompleted();
}
});
}
uiObs = null;
}
private Observable<String> getParallelObservable(String[] methods) {
return Observable.from(methods).flatMap(new Func1<String, Observable<String>>() {
@Override
public Observable<String> call(String s) {
return Observable.just(s).subscribeOn(Schedulers.io()).map(new Func1<String, String>() {
@Override
public String call(String s) {
if ("async1".equals(s)) {
async1();
} else if ("async2".equals(s)) {
async2();
} else if ("async3".equals(s)) {
async3();
} else if ("async4".equals(s)) {
async4();
} else if ("async5".equals(s)) {
async5();
} else if ("async6".equals(s)) {
async6();
} else if ("async7".equals(s)) {
async7();
} else if ("async8".equals(s)) {
async8();
}
return s;
}
});
}
});
}
/**
* 获取被重写的方法
* @return
*/
private List<String> getOverrideMethods() {
List<String> overrideMethods = new ArrayList<>();
Method[] bfs = getClass().getDeclaredMethods();
Method[] afs = ParallelTask.class.getDeclaredMethods();
for (Method bm : bfs) {
for (Method am : afs) {
if (bm.getName().equals(am.getName()) &&
bm.getReturnType().equals(am.getReturnType())) {
Class[] bc = bm.getParameterTypes();
Class[] ac = am.getParameterTypes();
if (bc.length == ac.length) {
boolean isEqual = true;
for (int i = 0; i < bc.length; i++) {
if (!bc[i].equals(ac[i])) {
isEqual = false;
break;
}
}
if (isEqual) {
String name = bm.getName();
overrideMethods.add(name);
}
}
}
}
}
return overrideMethods;
}
}
实现了ParallelTask抽象类,可以同时执行8个任务,用户可以自己增加个数。用户可以创建一个ParallelTask类,然后实现async1方法,按照自己的需求实现其他方法即可。