gpt4 book ai didi

java - ScheduledExecutorService 超时后中断

转载 作者:行者123 更新时间:2023-12-02 13:36:50 24 4
gpt4 key购买 nike

我需要实现一个计划执行程序服务,该服务每隔 x 秒运行一个线程。如果线程执行时间超过 y 秒,则应中断线程执行。我尝试使用 ScheduledExecutorService 来实现该解决方案,该服务具有用于间隔的可配置参数,但没有用于超时的参数。我有一些想法,我想听听您对实现/技术的建议。

最佳答案

这有帮助吗?任务每 10 秒开始一次,需要 5 秒才能完成,当超时(3 秒)时,您将收到 InterruptedException。

import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Worker implements Runnable {
ListeningExecutorService listeningExecutorService;
ScheduledExecutorService scheduledExecutorService;
Runnable task;

public Worker(ListeningExecutorService listeningExecutorService, ScheduledExecutorService scheduledExecutorService, Runnable task) {
this.listeningExecutorService = listeningExecutorService;
this.scheduledExecutorService = scheduledExecutorService;
this.task = task;
}

@Override
public void run() {
ListenableFuture future = listeningExecutorService.submit(task);
Futures.withTimeout(future, 3, TimeUnit.SECONDS, scheduledExecutorService);
}

public static void main(String[] args) {
ListeningExecutorService listeningExecutorService = MoreExecutors
.listeningDecorator(Executors.newCachedThreadPool());
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
Worker worker = new Worker(listeningExecutorService, scheduledExecutorService, new Runnable() {
@Override
public void run() {
System.out.println("Now begin: " + new Date());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Now end: " + new Date());
}
});
scheduledExecutorService.scheduleAtFixedRate(worker, 0, 10, TimeUnit.SECONDS);
}
}

关于java - ScheduledExecutorService 超时后中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42946627/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com