有个功能需要同时上传N个文件。代码如下:
ApiService as = ApiManager.getApiService();
final ExecutorService es = Executors.newFixedThreadPool(9);
final int count = Bimp.tempSelectBitmap.size();
final CountDownLatch finishedLatch = new CountDownLatch(count);
final long start = System.currentTimeMillis();
for (int k = 0; k < count; k++) {
final String fp = Bimp.tempSelectBitmap.get(k).getImagePath();
RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), new File(fp));
as.uploadAttach(fbody)
.subscribeOn(Schedulers.from(es))
.observeOn(Schedulers.computation())
.subscribe(new Subscriber<UploadAttachJSON>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
finishedLatch.countDown();
Log.e("UPLOAD FAILED -------->", fp);
}
@Override
public void onNext(UploadAttachJSON uploadAttachJSON) {
finishedLatch.countDown();
sb.append(uploadAttachJSON.url).append(",");
Log.e("UPLOADED IMAGE URL -->", uploadAttachJSON.url);
h.post(new Runnable() {
@Override
public void run() {
pd.setMessage("正在上传... " + (count - finishedLatch.getCount()) + "/" + count);
}
});
}
});
}
try {
finishedLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
Log.e("IMAGE UPLOAD COMPLETED", (end - start) + "");
es.shutdown();
以上为并行的写法。从线程池中拿出N个线程来同时上传这N个文件。
串行写法: .subscribeOn(Schedulers.io())
或者 用Observable.merge
来合并这些请求。
结果发现并行和串行所花费的时间几乎都差不多。。 是不是和android底层有关?这些网络请求其实最后都被底层给block了,然后串行出去?
PHPz2017-04-17 17:53:29
考慮すべき要素は数多くあります
1. 独自のコード実装
2. データを受信するためのサーバー コードの実装