在测试中杀死一个Java线程 [英] killing a java thread in test
问题描述
我正在编写一种有关编程的教程(在github上将是Java仓库),用户可以在其中克隆仓库并在空方法内编写自己的代码来解决算法问题.在编写代码之后,他们可以启动单元测试以检查其解决方案是否正确,以及该解决方案是否可以在不到一定的时间内完成执行(以确保他们找到了最有效的解决方案). 因此,我的存储库将包含许多带有空方法的类以及所有非空单元测试,以检查用户将编写的代码.
I'm writing a sort of tutorial about programming (it will be a Java repo on github) where users can clone the repo and write their own code inside empty methods to solve algorithmic problems. After they write their code, they can launch unit tests to check if their solution is correct and if it completes execution in less than a certain time (to assure they found the most efficient solution). So my repo will contain a lot of classes with empty methods and all the non-empty unit tests to check the code the users will write.
我在JUnit测试中所做的就是这样:
What I'm doing in the JUnit tests is something like that:
// Problem.solveProblem() can be a long running task
Thread runner = new Thread(() -> Problem.solveProblem(input));
runner.start();
try {
Thread.currentThread().sleep(500);
}
catch (InterruptedException e) {
e.printStackTrace();
}
if (runner.isAlive()) {
fail("Your algorithm is taking too long.");
runner.stop();
}
现在,如果用户编写了未优化的算法,则测试会正确失败,但是runner
线程将继续运行(因此也会执行测试线程)直到终止为止,尽管这可能在几分钟后发生,但我呼叫running.stop()
.因此,我的测试可以持续几分钟而不是我想要的几秒钟.
Now, if a user writes a not optimized algorithm, the test fails correctly, but the runner
thread will continue to run (and so will do the test thread) until it terminates, which can happen after minutes, though I call running.stop()
. So I have tests that can last minutes instead of seconds like I'd like.
我知道如何优雅地杀死Java中的线程,但是在这种情况下,我不希望用户处理多线程问题(例如检查/更新共享变量):我只希望他们只编写代码以解决问题.
I know how to gracefully kill a thread in Java, but in this case I don't want the users to take care of multithreading issues (like checking/updating shared variables): I just want them to write only the code to solve the problem.
所以我的问题是:有没有一种方法可以突然终止Java中的线程?如果没有,我还有其他方法可以实现我的目标吗?
So my question is: is there a way to abruptly kill a thread in Java? If not, is there any other approach I could follow to accomplish my goal?
谢谢, 安德里亚