可以使用的ExecutorService,設置超時值,並取消今後如果超時被傳遞以請求線程中斷:
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<?> future = null;
try {
Runnable r = new Runnable() {
@Override
public void run() {
while (true) {
// it the timeout happens, the thread should be interrupted. Check it to let the thread terminates.
if (Thread.currentThread().isInterrupted()) {
return;
}
exampleMethod();
}
}
};
future = executorService.submit(r);
future.get(10, TimeUnit.SECONDS);
}
// time is passed
catch (final TimeoutException e) {
System.out.println("I was to slow");
// you cancel the future
future.cancel(true);
}
// other exceptions
catch (Exception e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
}
這取決於你的方法在做什麼。通常阻塞操作會允許超時或中斷。 – shmosel
可能重複的[如何超時線程](http://stackoverflow.com/questions/2275443/how-to-timeout-a-thread) – tucuxi
當然,我可以寫一些自己的超時包裝?有可能的? – rilav