您的位置:軟件測(cè)試 > 開源軟件測(cè)試 > 開源單元測(cè)試工具 > junit
Junit測(cè)試中多線程的坑
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時(shí)間:[ 2016/9/21 10:45:35 ] 推薦標(biāo)簽:單元測(cè)試 Junit

  昨晚用Junit測(cè)試多線程代碼如下:
private int i = 3;
@Test
public void test() {
for (int i = 0; i < this.i; i ++) {
new Thread(new Runner()).start();
}
}
class Runner implements Runnable {
@Override
public void run() {
System.out.printlun(123);
}
}
  發(fā)現(xiàn)運(yùn)行后居然沒有任何輸出…我又運(yùn)行了好幾次,有時(shí)又有1~2句輸出,但是始終不全…
  當(dāng)時(shí)還以為程序有錯(cuò),clean了class繼續(xù),還是一樣的,早上起來查了下百度,才明白,原來Junit只管自己的運(yùn)行,是說當(dāng)Junit執(zhí)行完畢后,會(huì)關(guān)閉程序,不會(huì)關(guān)心是否還有自己?jiǎn)?dòng)的后臺(tái)線程在運(yùn)行。當(dāng)Junit運(yùn)行完畢后,如果后臺(tái)線程還沒有執(zhí)行完畢,那么也是不會(huì)再執(zhí)行了,所以出現(xiàn)了昨天的情況…
  我始終對(duì)多線程的執(zhí)行過程沒有意識(shí)呢…主線程和后臺(tái)線程的關(guān)系和執(zhí)行一定要搞清楚呢…
  現(xiàn)在既然搞清楚了,那好辦了,下面代碼展示如何優(yōu)雅的將Junit主線程設(shè)置為同步線程:
private int i = 3;
/*
* 線程計(jì)數(shù)器
* 將線程數(shù)量初始化
* 每執(zhí)行完成一條線程,調(diào)用countDown()使計(jì)數(shù)器減1
* 主線程調(diào)用方法await()使其等待,當(dāng)計(jì)數(shù)器為0時(shí)才被執(zhí)行
*/
private CountDownLatch latch = new CountDownLatch(i);
@Test
public void test() {
for (int i = 0; i < this.i; i ++) {
new Thread(new Runner()).start();
}
try {
latch.await(); // 主線程等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
class Runner implements Runnable {
@Override
public void run() {
System.out.printlun(123);
latch.countDown(); // 執(zhí)行完畢,計(jì)數(shù)器減1
}
  這樣改變代碼之后,一切正常了!

軟件測(cè)試工具 | 聯(lián)系我們 | 投訴建議 | 誠(chéng)聘英才 | 申請(qǐng)使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd