多线程结合CountDownLatch实现图片下载功能

126 阅读1分钟

多线程结合CountDownLatch实现图片下载功能

List<Map<String, Object>> downActList=Lists.... // 获取图片附件id
if (!CollectionUtils.isEmpty(downActList)) {
 long startTime = System.currentTimeMillis();
 ThreadFactory exportAuditThreadFactory = new ThreadFactoryBuilder().setNameFormat("audit-export-pic-pool").build();
 ExecutorService threadPool = new ThreadPoolExecutor(5, 5, 0L,
         TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(50), exportAuditThreadFactory);
 CountDownLatch countDownLatch = new CountDownLatch(downActList.size());
 for (Map<String, Object> obj : downActList) {
     threadPool.execute(() -> {
         try {
             String businessCode = (String) obj.get("businessCode");
             String attachmentId = (String) obj.get("attachmentId");
             String queryDownloadUrl = (String) obj.get("queryDownloadUrl");
             URL url = new URL(queryDownloadUrl);
             HttpURLConnection conn = (HttpURLConnection) url.openConnection();
             conn.setRequestMethod("GET");
             conn.setConnectTimeout(5 * 1000); // 5秒超时
             InputStream inStream = conn.getInputStream();
             byte[] byteArray = readInputStream(inStream);
             // 附件与businessCode对应处理-byteArray图片
             this.handledFiles(auditRunBadWithTaskInfoExportList, businessCode, attachmentId, byteArray);
         } catch (Exception e) {
             e.printStackTrace();
             logger.error("图片下载线程异常", e);
         } finally {
             countDownLatch.countDown();
         }
     });
 }
 // 等待数据初始化,阻塞
 countDownLatch.await();
 logger.info("线程执行时间,{}", System.currentTimeMillis() - startTime);
}