我有一个循环的函数,我打算并行但不知道多线程的负载是否会超过并发的好处。将一个for循环转换为一个多线程块
我只需要发送不同的日志文件到相应的接收器。对于时间来说,可以说接收器的数量不会超过10个。而不是将日志文件背靠背发送,如果我将它们全部并行发送,效率会更高吗?
for(int i=0; i < receiversList.size(); i++)
{
String receiverURL = serverURL + receiversList.get(i);
HttpPost method = new HttpPost(receiverURL);
String logPath = logFilesPath + logFilesList.get(i);
messagesList = readMsg(logPath);
for (String message : messagesList) {
StringEntity entity = new StringEntity(message);
log.info("Sending message:");
log.info(message + "\n");
method.setEntity(entity);
if (receiverURL.startsWith("https")) {
processAuthentication(method, username, password);
}
httpClient.execute(method).getEntity().getContent().close();
}
Thread.sleep(500); // Waiting time for the message to be sent
}
也请告诉我如何才能使它平行,如果它会工作?我应该手动执行还是使用ExecutorService?
谢谢你这么多。我在不同的机器上有日志文件和接收器,所以在这种情况下,我会达到你提到的另一种情况的性能吗? – aneela
如果您有多台不同的机器,则将日志文件发送到不同的机器可能确实会提高性能。很难真正知道没有更多细节@aneela。 – Gray