gpt4 book ai didi

java - 从外部中止 JUnit 线程

转载 作者:太空宇宙 更新时间:2023-11-04 09:40:41 25 4
gpt4 key购买 nike

我正在编写一个使用 JUnit 的测试应用程序。我们使用可运行类手动启动 JUnit

public class MyLauncher implements Runnable {

public void run() {
launchJunit();
}

private void launchJunit() {
LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request().selectors(selectors).build();
Launcher launcher = LauncherFactory.create();
launcher.execute(request);
}
}

使用

public class MyApplication {

public void main(String[] args) {
ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
ScheduledFuture<?> thread = null;
thread = pool.schedule(new MyLauncher());

//
// do some magic
//

thread.cancel(true);
// or
pool.shutdownNow();
}
}

但是,thread.cancel()pool.shutdownNow() 都不会中断 JUnit 线程。除非我在应用程序末尾使用 System.exit(0),否则 JUnit 将继续运行。有没有办法中断 JUnit 线程?我正在使用 JUnit 扩展,因此我可以在必要时 Hook 一些回调。

最佳答案

我已经尝试过了,对我来说,线程似乎被 pool.shutdownNow() 中断,但有一点延迟。

您可以使用方法https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#awaitTermination等待它终止。

当我像这样重新排列你的代码时:

public static void main(String[] args) throws InterruptedException {
ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
ScheduledFuture<?> thread = null;
MyLauncher myLauncher = new MyLauncher();
thread = pool.schedule(myLauncher, 0, TimeUnit.MILLISECONDS);

Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
System.out.println("Number of threads: " + threadSet.size());


thread.cancel(true);
pool.shutdownNow();

System.out.println("Waiting for thread to terminate...");
pool.awaitTermination(10, TimeUnit.SECONDS);

threadSet = Thread.getAllStackTraces().keySet();
System.out.println("Number of threads: " + threadSet.size());
}

我得到输出:

Number of threads: 6
Waiting for thread to terminate...
Number of threads: 5

关于java - 从外部中止 JUnit 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56019395/

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