在外部中止JUnit线程

时间:2019-05-07 09:20:18

标签: java junit

我正在编写一个使用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扩展,因此如有必要,可以挂入一些回调。

1 个答案:

答案 0 :(得分:1)

我已经尝试过了,对我来说,线程似乎被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());
}

我得到输出:

  

线程数:6
  等待线程终止...
  线程数:5