通过 Future 来实现取消
private static ExecutorService taskExec = Executors.newCachedThreadPool();
public static void timeRun(Runnable r, long timeout, TimeUnit unit)
throws InterruptedException {
Future<?> task = taskExec.submit(r);
try {
task.get(timeout, unit);
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (TimeoutException e) {
e.printStackTrace();
} finally {
task.cancel(true);
}
}最后更新于