多线程下载材料与主线程同步

多线程下载材料与主线程同步

业务场景:接收三方资源,用户实时查看下载

1、自定义线程池

private final LinkedBlockingQueue<Runnable> blockingQueue = new LinkedBlockingQueue<>(2048);

@Bean
public ExecutorService executorService (){
    ExecutorService executor =
                    new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() * 2,
                            Runtime.getRuntime().availableProcessors() * 4,
                            10, TimeUnit.SECONDS, blockingQueue,
                            ThreadPoolManager.namedThreadFactory("threadpool_name"),
                            new ThreadPoolExecutor.CallerRunsPolicy()
                    );
    retturn executor;
}

2、下载材料方法

//下载文件
public void downloadFile(List fileList) {
        CountDownLatch latch = new CountDownLatch(fileList.size());
        AtomicInteger failNum = new AtomicInteger(0);
        fileList.forEach(pojo->{
            executorService.execute(()->{
                //上传文件
                uploadFile(pojo,latch,failNum);
            });
        });
        try {
            //8秒没有完成,自动取消
            latch.await(8,TimeUnit.SECONDS);
        }catch (Exception e){
            //do exception handling
        }
        if(sbjl.get() != 0){
            //business processing after failure
        }
}

3、上传材料


public void uploadFile(Pojo pojo,CountDownLatch latch,AtomicInteger failNum){
    InputStream intstream = null;
    try {
        URL url = new URL(pojo.getUrl());
        HttpURLConnection huc = (HttpURLConnection)url.openConnection();
        huc.setRequestMethod("GET");
        huc.setDoOutput(true);
        huc.setDoInput(true);
        huc.setUseCaches(false);
        huc.setConnectTimeout(2000);
        huc.setReadTimeout(7000);
        intstream = huc.getInputStream();
        UploadRestul uploadRestul = FileUtis.upload(intstream,fileName);
        pojo.setUrl(uploadRestul.getUrl());
    }catch (Exception e){
        failNum.incrementAndGet();
    }finally {
        latch.countDown();
        if(!Objects.isNull(intstream)){
            try {
                 intstream.close();
            }catch (IOException e){
             log.info("下载材料关闭流失败");
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值