我不知道爲什麼junit具有以下行爲:當執行程序遇到Thread.sleep時,爲什麼線程無睡眠或拋出InterruptedException?
當我在線程有睡眠行爲(Thread.sleep())時將線程提交到執行程序(fixedThreadPool或其他)時,我發現線程馬上結束!沒有睡覺,沒有中斷的Excetion。
我想知道爲什麼?
(我知道下面的設計並不好,但我只是想說明上述問題)
@Test
public void executorPoolTest(){
ExecutorService cachedThreadPool =
Executors.newFixedThreadPool(10);
//Executors.newCachedThreadPool();
for (int i = 0; i < 1000; i++) {
final int index = i;
cachedThreadPool.execute(new Runnable() {
public void run() {
System.out.println(index);
try {
Thread.sleep(5000);
System.out.println(index+"_");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
//no matter whether you call shutdown, the above program will ends quickly.
cachedThreadPool.shutdown();
}
上述程序不打印任何號碼+「_」,很奇怪。 但是,如果上述方法在main方法(我的意思是:public static void main(String [] args))中運行,則行爲是正常的,線程將休眠,並且可以打印「_」。
我想知道爲什麼?在junit框架中發生了什麼?如果是這樣,我不能使用junit來測試執行者涉及的方法嗎?
junit版本是4.12。
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
啊,我明白了!你的意思是說,Junit的主線程結束了,因此,這個測試單元中的線程結束了。 – jixuan1989