gpt4 book ai didi

java - 如何提高多线程的性能

转载 作者:行者123 更新时间:2023-11-29 08:26:42 26 4
gpt4 key购买 nike

我用谷歌搜索并找到了使用多线程的最佳方法,但它在 100 条记录时失败,它给出了 504 状态代码。是否有任何改进以下代码的余地?

@Scheduled(fixedRate = 5000)
public ResponseEntity<Object> getData(List<JSONObject> getQuoteJson, String username,
String authorization) throws ParseException, IOException, Exception {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Access-Control-Allow-Origin", "*");
CompletableFuture<JSONArray> future = null;
JSONArray responseArray = new JSONArray();
try {
executor = Executors.newFixedThreadPool(getQuoteJson.size());
for (int i = 0; i < getQuoteJson.size(); i++) {
JSONObject jsonObject = (JSONObject) getQuoteJson.get(i);
future = CompletableFuture.supplyAsync(() -> {
JSONObject response = asynCallService.getDataAsyncService(jsonObject, productCode, authorization);
responseArray.add(response);
return responseArray;
}, executor);
}
return new ResponseEntity<Object>(future.get(), responseHeaders, HttpStatus.OK);
} catch (Exception e) {
throw e;
} finally {
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (Exception e) {
}
}

}

最佳答案

不要每次都创建和关闭executor,使用单例cached thread pool .由于重复创建线程是不必要的并且 expensive ,线程池的好处是保持线程存在。

关于java - 如何提高多线程的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52164167/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com