【发布时间】:2016-09-27 06:02:16
【问题描述】:
不知道junit为什么会有以下行为:
当我将一个线程提交给执行器(fixedThreadPool 或其他),而该线程具有睡眠行为(Thread.sleep())时,我发现该线程立即结束!没有睡眠,没有中断的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 来测试 executor 涉及的方法吗?
junit 版本是 4.12。
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
【问题讨论】:
标签: java multithreading junit executorservice thread-sleep