import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONException; import com.alibaba.fastjson.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.*; public class ThreadHttpRequest { // 申明线程池 ExecutorService executorServie = new ThreadPoolExecutor(3, 12, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(200)); public Map ShiPinThreadHandle(List<Caculator> caculators,RestUtils restUtils) throws JSONException, IOException, InterruptedException, ExecutionException { // 组合线程请求参数 JSONArray requestParameterArray = new JSONArray(); for (int i = 0; i < caculators.size(); i++) { Caculator caculator = caculators.get(i); JSONObject obj = new JSONObject(); obj.put(FinalFieldName.REQUESTURL, caculator.getRequestUrl()); obj.put(FinalFieldName.PARAMDATA, caculator.getDataType()); obj.put(FinalFieldName.APINAME, caculator.getApiName()); obj.put(FinalFieldName.REQUESTYPE, caculator.getRequesType()); requestParameterArray.add(obj); } // 申明数据回调处理类List<Future<JSONObject>> List<Future<JSONObject>> futures = new ArrayList<Future<JSONObject>>(); for (int i = 0; i < requestParameterArray.size(); i++) { JSONObject singleobje = requestParameterArray.getJSONObject(i); // 申请单个线程执行类 ShiPinThreadHandleRequest call = new ShiPinThreadHandleRequest(singleobje,restUtils); // 提交单个线程 Future<JSONObject> future = executorServie.submit(call); // 将请求过的数据移除 requestParameterArray.remove(i); // 将每个线程放入线程集合, 这里如果任何一个线程的执行结果没有回调,线程都会自动堵塞 futures.add(future); } // 所有线程执行完毕之后会执行下面的循环,然后通过循环每个个线程后执行线程的get()方法每个线程执行的结果 Map<String,String> map = new HashMap<String,String>(); for (Future<JSONObject> future : futures) { JSONObject json = future.get(); // 可能需要使用缓存,将查询的数据放入缓存 map.put(json.getString(FinalFieldName.APINAME), (String) json.get(FinalFieldName.APIVALUE)); } // 关闭线程池 executorServie.shutdown(); // 这里将查询的数据返回,如果放入缓存则此处返回空 return map; } }
标签:java,FinalFieldName,线程,obj,new,import,ThreadHttpRequest From: https://www.cnblogs.com/mingruifeng/p/16837494.html