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();
}
posted @ 2023-07-28 14:43  jason_bo  阅读(585)  评论(0编辑  收藏  举报