Java连续循环(循环无需等待)

vto*_*mak 1 java iterator while-loop

我希望有一个循环连续运行而无需等待循环中的东西.例如,在下面的示例中,我想迭代一个列表并调用一个名为doS​​omething()的方法,并且一旦调用doSomething()方法,我希望循环继续到第二个项目,第三个项目,等......

 while(it.hasNext())
 {
    MyObject obj = (MyObject)it.next();
    doSomething(obj);
 }
Run Code Online (Sandbox Code Playgroud)

它可以用轮询器完成,但我不想用轮询器来完成.

感谢您的帮助.

EdC*_*EdC 5

为此,您需要运行多个线程,因此多个调用可以并行运行.您可以手动执行此操作,但最好使用现有的实用程序,例如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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

使用此代码,所有循环都会安排执行doSomething方法.完成后,它将继续执行下一次执行.实际的doSomething由管理的10个线程之一运行ThreadPoolExecutor.