当前位置:网站首页>2021-08-11 for循环结合多线程异步查询并收集结果

2021-08-11 for循环结合多线程异步查询并收集结果

2022-08-11 06:44:00 yy1209357299

     JsonResult jsonResult = new JsonResult();
    ExecutorService executorService = Executors.newCachedThreadPool();
    HashMap<String,String> map = new HashMap<>();
    for(int i=0;i<jsonArray.size();i++){
                final int j = i;
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        synchronized (this){
                            String name = jsonArray.getJSONObject(j).getString("1");
                            String id = jsonArray.getJSONObject(j).getString("2");
                            String url = null;
                            try {
                                url = getUrl(id);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            map.put(name,url);
                        }
                    }
                });

            }
    executorService.shutdown();
    while(true){
        if(executorService.isTerminated()){
            break;
        }
    }
    if(map.size()>0){
        jsonResult.setCode("200");
        jsonResult.setResult(map);
    }else {
        jsonResult.setCode("300");
        jsonResult.setResult("无资源");
    }
原网站

版权声明
本文为[yy1209357299]所创,转载请带上原文链接,感谢
https://blog.csdn.net/yy1209357299/article/details/119593627