junit 5 默认使用 @timeout 注解配合 assertthrows(timeoutexception.class) 来验证超时,但这仅检查执行时间,不会强制中断线程。要实现抢占式中断,必须使用 executorservice 提交任务并调用 future.get(timeout, timeunit.seconds),随后通过 future.cancel(true) 发送中断信号。

如何验证代码在指定时间内完成?
要验证代码在指定时间内完成,可以使用 JUnit 5 的 @Timeout 注解。当方法执行超过设定时间时,测试会抛出 org.junit.jupiter.api.extension.TimeoutException。这种方法简单直接,但底层实现依赖于轮询或等待,无法真正抢占正在运行的线程。

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
public class SimpleTimeoutTest {
@Test
@Timeout(value = 1, unit = java.util.concurrent.TimeUnit.SECONDS)
public void testShouldPass() throws InterruptedException {
Thread.sleep(500);
}
}
如何实现真正的抢占式超时中断?
要实现真正的抢占式超时中断,需要借助 java.util.concurrent.ExecutorService。将待测逻辑封装为 Callable 或 Runnable 提交给线程池,然后调用 Future.get() 并设置超时时间。如果超时,捕获 TimeoutException 并调用 future.cancel(true) 以尝试中断线程。

import org.junit.jupiter.api.Test;
import java.util.concurrent.*;
public class PreemptiveTimeoutTest {
@Test
public void testPreemptiveTimeout() throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Void> task = () -> {
Thread.sleep(5000); // 模拟长时间运行
return null;
};
Future<Void> future = executor.submit(task);
try {
future.get(1, TimeUnit.SECONDS);
} catch (TimeoutException e) {
future.cancel(true); // 发送中断信号
} finally {
executor.shutdown();
}
}
}
中断信号对阻塞操作有效吗?
中断信号(InterruptedException)只对响应中断的阻塞操作有效,如 Thread.sleep()、Object.wait() 或 Lock.lockInterruptibly()。对于不响应中断的操作(如某些 I/O 操作或无限循环),cancel(true) 可能无效,线程仍会继续运行直到自然结束或 JVM 退出。

















