Junit在多執行緒中遇見的坑

2021-10-20 01:38:21 字數 1778 閱讀 5722

junit使用注意事項:

junit單元測試不支援多執行緒。。

當新建執行緒,junit單元測試在主線程執行結束後就關閉,不會等子執行緒執行結束。main方法則不會存在這樣的問題。

方法1:使用junit做多執行緒測試,發現程式並不會卡在讀的執行緒中,理論上到讀執行緒獲取到鎖後,由於沒有外界條件操作,是卡死在read的方法中,但是如下**達不到響應的效果。

原因在於junit單元測試在主線程執行結束後就關閉了,不會等子執行緒執行結束。

public class threadtest1 

system.out.println("number = " + number);}}

// 對方法進行加鎖

private void write(int change)

}@test//首次嘗試當number未到完成寫,讀執行緒等待。

public void test3() throws interruptedexception

system.out.println("加1操作完成");

complete = true;

}).start();

//開啟執行緒減10000次

new thread(() ->

system.out.println("讀取結束");

}).start();

thread.sleep(1000);

}}

執行結果:

程式正常執行結束。

方法2:使用main方法來演示如上場景,當read獲取到鎖後程式會一直卡在此處。

package com.weidd.best.multithread;

import org.junit.test;

public class threadtest2

system.out.println("number = " + number);}}

// 對方法進行加鎖

private static void write(int change)

}//首次嘗試當number未到完成寫,讀執行緒等待。

public static void main(string args) throws interruptedexception

system.out.println("加1操作完成");

complete = true;

}).start();

//開啟執行緒減100次

new thread(() ->

system.out.println("讀取結束");

}).start();

thread.sleep(1000);

}}

對於junit單元測試,當@test注釋的單元測試方法執行時,實際上junit時將該方法作為引數傳給了junit.textui.testrunner類的main函式,並通過main函式進行執行(源**如下)。

package junit.textui;

public class testrunner extends basetestrunner

system.exit(success_exit); // success_exit = 0

} catch (exception e)

}}

JUnit單元測試中多執行緒的坑

junit單元測試方法不輸出 在junit的 test方法中啟用多執行緒,新啟動的執行緒會隨著 test主線程的死亡而不輸出 test public void testmultithread catch interruptedexception e thread.start try catch in...

Junit測試中多執行緒問題

這兩天使用junit測試,測試 中為了模擬實際場景開啟多執行緒,有的情況下,測試的功能本身就是多執行緒活動。測試半天沒有達到預想的效果,仔細研究發現 junit主線程執行完畢就結束了,不管後台執行緒。場景一 如果測試 中有多執行緒,可使用countdownlatc解決。private int i 3...

Realm多執行緒中的那些坑

個人在開發中遇到的一些小坑.可能會持續更新.1.realmobject自帶執行緒保護功能,只能在建立它的執行緒中訪問,在子執行緒中不能訪問。也就是說,如果你在主線程中new了乙個realmobject物件 user,那麼在子執行緒中是訪問不了user物件的。要想在子執行緒中訪問,必須先將user存入...