Tutte le altre risposte sono corrette, ma può essere fatto più robusto ed efficiente usando FutureTask.
Per esempio,
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
}
Se si esegue questa operazione più volte, il pool di thread è più efficiente perché memorizza nella cache i fili.
fonte
2009-08-08 21:46:47
Si prega di trovare una buona pratica e un po 'explantion qui: –
Wulfaz