サンプルとして、複数のホストに対してpingコマンドを発行するプログラムを作成しました。
import java.util.List; import java.util.ArrayList; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; public class Program { public static void main(String[] args) throws Exception { ExecutorService svc = Executors.newFixedThreadPool(3); try { List<Callable<Integer>> listCallable = new ArrayList<>(); for (String ipAddress : args) { listCallable.add(new PingCommand(ipAddress)); } List<Future<Integer>> listFuture = svc.invokeAll(listCallable); for (Future<Integer> future : listFuture) { System.out.println(future.get()); } } finally { svc.shutdown(); } } private static class PingCommand implements Callable<Integer> { private final String ipAddress; private PingCommand(String ipAddress) { this.ipAddress = ipAddress; } public Integer call() { try { String[] args = {"ping", ipAddress, "-c", "3"}; Process proc = new ProcessBuilder(args).start(); return proc.waitFor(); } catch (Exception e) { e.printStackTrace(); return -1; } } } }
参考
ExecutorService
Callable
Future