有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

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

    您可以使用方法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