Junit 多线测试 问题
問題
在使用Junit測試時(shí),發(fā)現(xiàn)在測試方法中啟動(dòng)新的線程,結(jié)果新開啟的線程未執(zhí)行,測試方法就結(jié)束了。難道Junit不支持多線程測試?
示例如下:
public class ThreadTest {@Testpublic void testSleep() {Thread t = new Thread(()-> {try {Thread.sleep(1000);} catch (Exception e) {}System.out.println("--------");});t.start();System.out.println("end...");} }第一想法就是 在junit中啟動(dòng)的線程都是daemon的?線程調(diào)用start() 方法后是不能修改線程的daemon狀態(tài)的。
還可能一種可能就是,執(zhí)行完主線程后就直接System.exit() 退出jvm。
下面我們分析下源碼,看看到底是什么情況
Debug模式下運(yùn)行 testSleep() 方法,如下:
通過 Junit 運(yùn)行 testSleep() 方法,我們發(fā)現(xiàn)Junit的運(yùn)行啟動(dòng)主類:
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.java執(zhí)行的方法 RemoteTestRunner.main(String arg[])
RemoteTestRunner.main() 源碼分析
public static void main(String JavaDoc[] args) {try {RemoteTestRunner testRunServer= new RemoteTestRunner();testRunServer.init(args);testRunServer.run();} catch (Throwable JavaDoc e) {e.printStackTrace(); // don't allow System.exit(0) to swallow exceptions} finally {// fix for 14434System.exit(0);} }從代碼中我們發(fā)現(xiàn),當(dāng)執(zhí)行完testSleep()方法的主線程時(shí),就會(huì)調(diào)用 finally里面的 System.exit(0) 方法,讓JVM強(qiáng)制退出。這是在testSleep()方法中啟動(dòng)的新線程也就強(qiáng)制停止了,而不會(huì)打印線程中輸出的信息。
解決辦法
最簡單的解決辦法如下:
@Test public void testSleep() throws InterruptedException {Thread t = new Thread(()-> {try {Thread.sleep(1000);} catch (Exception e) {}System.out.println("--------");});t.start();System.out.println("end...");t.join(); // TimeUnit.SECONDS.sleep(1000);}也可以使用 FutrueTask、CountDownLatch等。
想了解更多精彩內(nèi)容請(qǐng)關(guān)注我的公眾號(hào)
本人簡書blog地址:http://www.jianshu.com/u/1f0067e24ff8????
點(diǎn)擊這里快速進(jìn)入簡書
GIT地址:http://git.oschina.net/brucekankan/
點(diǎn)擊這里快速進(jìn)入GIT
總結(jié)
以上是生活随笔為你收集整理的Junit 多线测试 问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring mvc 启动配置文件加载两
- 下一篇: java 中的内省 introspect