Todas las otras respuestas son correctas pero se pueden hacer más robusto y eficiente usando FutureTask.
Por ejemplo,
private static final ExecutorService THREAD_POOL
= Executors.newCachedThreadPool();
private static <T> T timedCall(Callable<T> c, long timeout, TimeUnit timeUnit)
throws InterruptedException, ExecutionException, TimeoutException
{
FutureTask<T> task = new FutureTask<T>(c);
THREAD_POOL.execute(task);
return task.get(timeout, timeUnit);
}
try {
int returnCode = timedCall(new Callable<Integer>() {
public Integer call() throws Exception {
java.lang.Process process = Runtime.getRuntime().exec(command);
return process.waitFor();
}
}, timeout, TimeUnit.SECONDS);
} catch (TimeoutException e) {
// Handle timeout here
}
Si haces esto en varias ocasiones, el grupo de subprocesos es más eficiente, ya que almacena en caché los hilos.
Por favor, encontrar una buena práctica y algo explantion aquí: –
Wulfaz