为此,您需要运行多个线程,以便多个调用可以并行运行。您可以手动执行此操作,但最好使用现有的实用程序,例如ThreadPoolExecutor
. 这需要Runnables
并并行运行它们。
例如
// Create an executor that can run up to 10 jobs in parallel.
ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 5, TimeUnit.Seconds, new LinkedBlockingQueue());
while(it.hasNext()) {
// NB: Final is needed so that this can be accessed within the anonymous inner class
final MyObject obj = (MyObject)it.next();
// Queue up the doSomething to be run by one of the 10 threads
executor.execute(new Runnable() {
public void run() {
doSomething(obj);
}
}
}
使用这段代码,循环所做的就是安排 doSomething 方法的执行。之后,它继续执行下一次执行。实际的 doSomething 由ThreadPoolExecutor
.