tôi cảm thấy cách tiếp cận trong câu trả lời được chấp nhận là một chút lỗi thời. Với Java8, nó có thể được thực hiện đơn giản hơn nhiều.
Này, bạn có một phương pháp
MyResult conjureResult(String param) throws MyException { ... }
sau đó bạn có thể làm điều này (tiếp tục đọc, điều này chỉ là để cho thấy phương pháp này):
private final ExecutorService timeoutExecutorService = Executors.newSingleThreadExecutor();
MyResult conjureResultWithTimeout(String param, int timeoutMs) throws Exception {
Future<MyResult> future = timeoutExecutorService.submit(() -> conjureResult(param));
return future.get(timeoutMs, TimeUnit.MILLISECONDS);
}
tất nhiên, ném ngoại lệ là xấu, đây là phiên bản mở rộng chính xác với xử lý lỗi thích hợp, nhưng tôi khuyên bạn nên kiểm tra cẩn thận, có thể bạn muốn thực hiện một số việc khác (ghi nhật ký, trả lại thời gian chờ trong kết quả mở rộng, v.v.):
private final ExecutorService timeoutExecutorService = Executors.newSingleThreadExecutor();
MyResult conjureResultWithTimeout(String param, int timeoutMs) throws MyException {
Future<MyResult> future = timeoutExecutorService.submit(() -> conjureResult(param));
try {
return future.get(timeoutMs, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
//something interrupted, probably your service is shutting down
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} catch (ExecutionException e) {
//error happened while executing conjureResult() - handle it
if (e.getCause() instanceof MyException) {
throw (MyException)e.getCause();
} else {
throw new RuntimeException(e);
}
} catch (TimeoutException e) {
//timeout expired, you may want to do something else here
throw new RuntimeException(e);
}
}
Nguồn
2016-12-13 17:47:29
Tuyệt vời! Làm việc hoàn hảo cho tôi. – Haych