我正在使用 Java 1.5 从命令行读取多个参数。参数是平面文件的名称。我遍历 main 方法中的参数并调用一个方法,该方法又创建了一堆线程来处理文件。我需要暂停循环,直到所有处理第一个参数的线程都完成,然后继续为第二个参数创建线程。如何在我的 main 方法中对参数进行排队或暂停循环执行,直到处理当前参数的所有线程完成?
最佳答案
使用线程池和执行器。查看 java.util.concurrent
包。
for(String argument:args){
//you said you want multiple threads to work on a single argument.
//create callables instead and use a ThreadPool
List<Callable<YourResult>> lstCallables = createCallablesFor(argument);
List<Future<YourResult>> futures = Executors.newCachedThreadPool().invokeAll(lstCallables);
for(Future<YourResult> future:futures){
//this get() waits until the thread behind the current future is done.
// it also returns whatever your callable might return.
future.get();
}
// at this point, all the threads working on the current argument are finished
// and the next loop iteration works on the next argument
}
关于java - 暂停执行 main 方法中的循环,直到所有线程完成 Java 1.5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33521063/