Java 线程任务超时设置
JDK 8
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<String> task = () -> {
test1();
return "Task excute success!";
};
Future<String> future = executor.submit(task);
try {
// 设置超时时间为20秒
String result = future.get(20, TimeUnit.SECONDS);
System.out.println(result);
} catch (TimeoutException e) {
e.printStackTrace();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
// 取消任务执行(如果任务还在执行中)
future.cancel(true);
// 关闭线程池
executor.shutdown();
}
本文来自博客园,作者:jason_bo,转载请注明原文链接:https://www.cnblogs.com/jasonboboblog/p/17587576.html