ScheduledExecutorService 超时停止
时间: 2024-01-13 20:19:54 浏览: 125
ScheduledExecutorService可以通过设置任务的超时时间来实现超时停止的功能。当任务执行时间超过设定的超时时间时,可以使用cancel方法来停止任务的执行。
下面是一个示例代码,演示了如何使用ScheduledExecutorService实现超时停止的功能:
```java
import java.util.concurrent.*;
public class TimeoutExample {
public static void main(String[] args) {
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
// 创建一个任务
Runnable task = () -> {
// 任务逻辑
System.out.println("Task is running...");
};
// 提交任务,并设置超时时间为2秒
ScheduledFuture<?> future = executor.schedule(task, 2, TimeUnit.SECONDS);
try {
// 等待任务执行完成,最多等待3秒
future.get(3, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// 处理中断异常
e.printStackTrace();
} catch (ExecutionException e) {
// 处理任务执行异常
e.printStackTrace();
} catch (TimeoutException e) {
// 超时停止任务的执行
future.cancel(true);
System.out.println("Task is timeout and stopped.");
}
// 关闭线程池
executor.shutdown();
}
}
```
在上述代码中,我们创建了一个ScheduledExecutorService,并提交了一个任务。通过调用schedule方法设置任务的超时时间为2秒。然后使用future.get方法等待任务执行完成,最多等待3秒。如果任务在超时时间内未完成,就会抛出TimeoutException异常,我们可以在catch块中调用future.cancel方法来停止任务的执行。
阅读全文
相关推荐


















