优艾设计网

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

优艾设计网 https://www.uibq.com 2023-04-18 19:38 出处:网络 作者:PS基础教程
有个功能需要同时上传N个文件。代码如下: ApiService as = ApiManager.getApiService();final ExecutorService es = Executors.newFixedThreadPool(9); final int count = Bimp.tempSelectBitmap.size(); final Cou

有个功能需要同时上传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()优艾设计网_PS问答) .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了,然后串行出去?


jimmy肖明 2022-07-12 21:08

优艾设计网_设计客

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


凭着良心做好人 2022-07-12 21:13

优艾设计网_设计备的网速是不是有限制


0

精彩评论

暂无评论...
验证码 换一张
取 消