Quiero leer varios archivos que utilizan un grupo de subprocesos, pero fallé.
@Test
public void test2() throws IOException {
String dir = "/tmp/acc2tid2999928854413665054";
int[] shardIds = new int[]{1, 2};
ExecutorService executorService = Executors.newFixedThreadPool(2);
for (int id : shardIds) {
executorService.submit(() -> {
try {
System.out.println(Files.readAllLines(Paths.get(dir, String.valueOf(id)), Charset.forName("UTF-8")));
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
El anterior es un ejemplo sencillo que escribí. Que no puede alcanzar mi propósito.
System.out.println(Files.readAllLines(
Paths.get(dir, String.valueOf(id)), Charset.forName("UTF-8")));
Esta línea no se ejecutará y no hubo advertencias. No sé por qué?
Se dispone a enviar tareas a ejecutar a continuación, poner fin a la prueba antes de esperar a que las tareas para completar. ExecutorService::submit
presentará la tarea a ejecutar en el futuro y volver inmediatamente. Por lo tanto, el ciclo for presenta las dos tareas a continuación extremos, y la función de prueba vuelve antes de que las tareas tenido el tiempo para completar.
Usted puede tratar de llamar ExecutorService::shutdown
después de que el bucle para informarle a la albacea que todas las tareas se han presentado. A continuación, utilice ExecutorService::awaitTermination
al bloque hasta que las tareas se han completado.
Por ejemplo:
@Test
public void test2() throws IOException {
String dir = "/tmp/acc2tid2999928854413665054";
int[] shardIds = new int[]{1, 2};
ExecutorService executorService = Executors.newFixedThreadPool(2);
for (int id : shardIds) {
executorService.submit(
() -> {
try {
System.out.println(Files.readAllLines(Paths.get(dir, String.valueOf(id)), Charset.forName("UTF-8")));
} catch (IOException e) {
e.printStackTrace();
}
});
}
executorService.shutdown();
executorService.awaitTermination(60, TimeUnit.SECONDS); //Wait up to 1 minute for the tasks to complete
}