我在 while 循环中使用不同的对象调用方法,但它需要时间,因为它将等待完成一个对象的方法执行,然后它将调用其他对象的方法,依此类推。
为什么我可以并行调用方法而无需等待完成方法执行?
找到下面的示例代码。
While (iter.hasNext){
Object value = iter.next();
result = method(value);
}
正如上面提到的代码方法的执行会发生一一的值
有什么方法可以并行调用而无需等待完成先前的值。
我建议你使用线程池:
ExecutorService executorService = Executors.newFixedThreadPool(10);
List<String> values = List.of("value1", "value2");
for (Object value : values) {
executorService.submit(() -> {
System.out.println(value);
});
}
通过此设置,列表的元素将被并行处理
基本上你有2个选择,取决于你是否需要处理每个案例, 或者您是否正在寻找任何一个(最快的、可能的或积极的)。 简而言之,您可以使用工作人员(线程)队列,也许像这样:
// Concurrent queue for workers
ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<>();
// Build the queue of defined interval - either for every case, or group them by some criteria (by 10, 100, ...)
// Create Callable workers (while building the queue)
List<Callable<int[]>> workers = new ArrayList<>();
for( int i = 1; i < THREADS; i++ )
workers.add( getAtomicResults );
// sizing parallelism might be important - CPU cores, -1 for kernel
THREADS = Math.max(1, -1 + Runtime.getRuntime().availableProcessors());
// Let workers do their jobs, collect the results - either find the solution or add another one ...
List<Future<int[]>> results;
ExecutorService executorService = Executors.newWorkStealingPool( THREADS - 1 );
try {
results = executorService.invokeAll( workers );
} catch ( InterruptedException e ) { return failedExecutor( e.getMessage() ); }
// collect the data, terminate or continue ...
for ( Future<int[]> future : results ) {
if ( future.isCancelled() )
return failedWorker( future.toString() );
try {
int[] result = future.get();
...
}
}
// Your atomic implementation ...
Callable<int[]> getAtomicResults = () -> {
}