2016-05-29 80 views
0

我不知道爲什麼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> 

回答

2

是的,因爲您並未等待您計劃完成的任務。如果你有其他的單元測試,你創建的線程仍然會繼續在後臺執行,但是你的測試會完成,因爲你沒有告訴它做任何事情。如果這是你唯一的測試,那麼沒有任何東西能夠保持這個進程的活躍狀態,所以測試套件將不會從線程輸出。

如果您在關機後致電awaitTermination然後它會在測試完成之前等待所有線程完成。

+0

啊,我明白了!你的意思是說,Junit的主線程結束了,因此,這個測試單元中的線程結束了。 – jixuan1989

相關問題