Один надежный способ (из многих) параллельно выполнять любой метод - запустить пул потоков, а затем назначить ему задачи и ждать, пока задачи завершатся sh.
public static ThreadPoolExecutor getExecutorService(int poolSize, int maxPoolSize{
int threadPoolshutDownTime = 10L;
ThreadPoolExecutor executorService= new ThreadPoolExecutor(poolSize, maxPoolSize, threadPoolshutDownTime, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
executorService.allowCoreThreadTimeOut(true); // allows the threadpool to shutdown if no task is assigned
return executorService;
}
Теперь вызовите это внутри вашего метода следующим образом:
public void a(List<Object> list) throws InterruptedException, ExecutionException {
List<Callable<Boolean>> callables = new ArrayList<>(list.size());
list.forEach(object ->callables.add(() -> return asynchMethod(object)));
for (Future<Boolean> booleanFuture : this.getExecutorService(1,4).invokeAll(callables)) {
booleanFuture.get(); //this will wait for the callables to be done!
}
}
Также измените ваш aysncMethod следующим образом:
private boolean asynchMethod(Object o) {
return o.doMagic(); //doMagic returns a boolean when completed
}