これで、タスクが1つずつ実行されます。コメントとして取得したコードのコメントを解除し、行にコメント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();