I do not know why junit has the following behavior:
When I submit a thread into a executor (fixedThreadPool or others) while the thread has a sleep behavior (Thread.sleep()), I find that the thread ends up immediately! No sleeping, no interruptedExcetion.
I wonder why?
(I know the following design is not good, but I just want to describe the above question)
@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();
}
The above program do not print any number+"_", very strange. However, if the above method is running in a main method (I mean: public static void main(String[] args)), the behavior is normal, the threads will sleep and "_" can be printed.
I wonder why? What happened in junit framework? If so, can't I use junit to test executor involved methods?
The junit version is 4.12.
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
Yes, because you're not waiting for the tasks you've scheduled to complete. If you have other unit tests, the threads you've created will still keep executing in the background, but your test will complete because you've not told it to do anything else. If that's your only test, there's nothing to keep the process alive, so the test suite will complete with no output from the threads.
If you call awaitTermination
after shutdown, then it will wait for all the threads to complete before the test finishes.
See more on this question at Stackoverflow