Android下,rxJava+retrofit 并發(fā)上傳文件和串行上傳文件的效率為什么差不多? 財富值49

科技 未結 2 1585
Yasu_Nana
Yasu_Nana 2022-09-21 19:35

有個功能需要同時上傳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來合并這些請求。

結果發(fā)現并行和串行所花費的時間幾乎都差不多。。 是不是和android底層有關?這些網絡請求其實最后都被底層給block了,然后串行出去?

2條回答
  •  曉曉菜鳥
    2022-09-21 20:30

    任何一個部分不是并發(fā)的,最后的結果就不是并發(fā)的

提交回復