以您现在获得的方式,任务将被一一执行。如果您取消注释您现在作为注释获得的代码并注释行RequestTask task = new RequestTask(requestItems.poll(), this, response);
,task.run();
您将获得并发执行。
因此,对于并发执行,它必须如下所示:
int threadNum = requestItems.size();
ExecutorService exs = Executors.newFixedThreadPool(threadNum);
for (int i = 0; i < threadNum; i++) {
ResponseInterface response = new CMSGOResponse();
exs.execute(new RequestTask(requestItems.poll(), this, response));
}
exs.shutdown();
while (! exs.isTerminated()) {
try {
exs.awaitTermination(1L, TimeUnit.DAYS);
}
catch (InterruptedException e) {
// you may or may not care here, but if you truly want to
// wait for the pool to shutdown, just ignore the exception
// otherwise you'll have to deal with the exception and
// make a decision to drop out of the loop or something else.
}
}
除此之外,我建议您不要将使用创建的线程数量绑定ExecutorService
到您要工作的任务数量。将其连接到主机系统的处理器数量通常是更好的方法。要获得处理器数量,请使用:Runtime.getRuntime().availableProcessors()
在像这样初始化的执行器服务中,您放置队列中的项目。但这在不获取总大小的情况下很好地工作,而是通过轮询Queue
直到它不返回额外的数据。
我的建议的最终结果可能如下所示:
final int threadNum = Runtime.getRuntime().availableProcessors();
final ExecutorService exs = Executors.newFixedThreadPool(threadNum);
while (true) {
final RequestItem requestItem = requestItems.poll();
if (requestItem == null) {
break;
}
final ResponseInterface response = new CMSGOResponse();
exs.execute(new RequestTask(requestItem , this, response));
}
exs.shutdown();