Tất cả các câu trả lời khác là chính xác nhưng nó có thể được thực hiện mạnh mẽ hơn và hiệu quả hơn khi sử dụng FutureTask.
Ví dụ,
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
}
Nếu bạn làm điều này nhiều lần, hồ bơi thread là hiệu quả hơn vì nó lưu trữ các chủ đề.
Nguồn
2009-08-08 21:46:47
Hãy tìm một thực hành tốt và một số explantion đây: –
Wulfaz