Android下,rxJava+retrofit 并发上传文件和串行上传文件的效率为什么差不多? 财富值49

2016-11-01 11:36发布

有个功能需要同时上传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了,然后串行出去?

2条回答

设备的网速是不是有限制

任何一个部分不是并发的,最后的结果就不是并发的

一周热门 更多>