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