Junit 多线测试 问题
生活随笔
收集整理的這篇文章主要介紹了
Junit 多线测试 问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題
在使用Junit測試時,發現在測試方法中啟動新的線程,結果新開啟的線程未執行,測試方法就結束了。難道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中啟動的線程都是daemon的?線程調用start() 方法后是不能修改線程的daemon狀態的。
還可能一種可能就是,執行完主線程后就直接System.exit() 退出jvm。
下面我們分析下源碼,看看到底是什么情況
Debug模式下運行 testSleep() 方法,如下:
通過 Junit 運行 testSleep() 方法,我們發現Junit的運行啟動主類:
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.java執行的方法 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);} }從代碼中我們發現,當執行完testSleep()方法的主線程時,就會調用 finally里面的 System.exit(0) 方法,讓JVM強制退出。這是在testSleep()方法中啟動的新線程也就強制停止了,而不會打印線程中輸出的信息。
解決辦法
最簡單的解決辦法如下:
@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等。
想了解更多精彩內容請關注我的公眾號
本人簡書blog地址:http://www.jianshu.com/u/1f0067e24ff8????
點擊這里快速進入簡書
GIT地址:http://git.oschina.net/brucekankan/
點擊這里快速進入GIT
總結
以上是生活随笔為你收集整理的Junit 多线测试 问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring mvc 启动配置文件加载两
- 下一篇: java 中的内省 introspect