【发布时间】:2022-01-21 16:44:18
【问题描述】:
我试图在执行 10 秒后停止长时间运行的方法,到目前为止,我遵循了 baeldung 上的计时器说明。
https://www.baeldung.com/java-stop-execution-after-certain-time#1-using-a-timer
当方法是对线程睡眠的简单调用时,它可以工作,但是当我使用子方法调用我的函数时,它不会停止。
我的实现如下所示:
class TimeOutTask extends TimerTask {
private Thread t;
private Timer timer;
TimeOutTask(Thread t, Timer timer){
this.t = t;
this.timer = timer;
}
public void run() {
if (t != null && t.isAlive()) {
t.interrupt();
timer.cancel();
}
}
}
class Execution implements Runnable {
private String carpeta;
private Experiment exp;
public Execution(String carpeta, Experiment exp) {
this.carpeta = carpeta;
this.exp = exp;
}
@Override
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
exp.executeExperiment(carpeta);
}
} catch (InterruptedException e) {
System.out.println("Fin de ejecución por tiempo");
}
}
}
我调用这个执行的方式是通过 executeTimedExperiment 方法
public Experiment() {
this.cases = new ArrayList<>();
}
private void executeTimedExperiment(String carpeta){
Thread t = new Thread(new Execution(carpeta,this));
Timer timer = new Timer();
timer.schedule(new TimeOutTask(t, timer), 10000);
t.start();
}
private void executeExperiment(String carpeta) throws InterruptedException {
String[] files = getFiles(carpeta);
Arrays.sort(files);
for (String file : files) {
executeCase(carpeta, file);
}
}
private boolean executeCase(String carpeta, String file) {
Graph g = readDataToGraph(carpeta + "/" + file);
Solution s = new ExactSolutionGenerator().ExactSolution(g);
addNewCase(file, s);
}
executeExperiment 方法是长时间运行的,我用 InterruptedException 对其进行了标记,但编译器告诉我永远不会抛出异常。
当我执行它时会发生什么,它可以正常运行而不会停止。
我不确定是否需要将 InterruptedException 添加到子方法或其他内容中,但如果可能的话,我希望不要触及子方法。
提前致谢。
【问题讨论】:
标签: java multithreading timer interrupt interrupt-handling