Java 8 soluzione CompletableFuture
:
public class FirstDoneWithCompletableFutureEx {
public static void main(String[] args) throws ExecutionException, InterruptedException {
int jobs = 10;
CompletableFuture<?>[] futures = new CompletableFuture[jobs];
for (int i = 0; i < jobs; i++) {
futures[i] = CompletableFuture.supplyAsync(() -> {
//computation
return new Object();
});
}
//first job done
Object firstDone = CompletableFuture.anyOf(futures).get();
}
}
Una soluzione java 5,6,7 con.210:
public class FirstDoneWithCompletionServiceEx {
public static void main(String[] args) throws InterruptedException, ExecutionException {
int jobs = 10;
ExecutorService executorService = Executors.newFixedThreadPool(jobs);
CompletionService<Object> completionService = new ExecutorCompletionService<>(executorService);
for (int i = 0; i < jobs; i++)
completionService.submit(
new Callable<Object>() {
@Override
public Object call() throws Exception {
//computation
return new Object();
}
}
);
//get first job done
Object firstDone = completionService.take().get();
executorService.shutdownNow();
}
}
potrebbe essere più facile (e più efficiente) per scoprire perché il programma prende a volte un paio di secondi e risolvere il problema ... – immibis
si consiglia [ExecutorCompletionService] (http://docs.oracle .com/javase/7/docs/api/java/util/concurrent/ExecutorCompletionService.html), ma sono d'accordo con @immibis – hsluo
@immibis Sembra che la generazione di labirinti (senza punti morti) sia solo un problema difficile, e ogni soluzione Ho trovato/posso pensare che richiede un pesante backtracking. – fredoverflow