junitが次のような動作をする理由が分かりません:エグゼキュータがThread.sleepを満たしているとき、スレッドがスリープせずに終了する、またはInterruptedExceptionをスローする理由を教えてください。
スレッドがスリープ動作(Thread.sleep())を行っている間にexecutor(fixedThreadPoolなど)にスレッドを送信すると、スレッドすぐに終わる!睡眠も中断もない。
なぜですか?
(私は次のような設計が良くないですけど、私は上記の質問を記述したい)
@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();
}
上記のプログラムは、任意の数+「_」、非常に奇妙に印刷されません。しかし、上記のメソッドがメインメソッド(つまり、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