如下代码, 打印语句无法正常执行
@Test
public void executorTest() {
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(()-> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("%s---睡了3秒钟\n", Thread.currentThread().getName());
});
}
可在System.exit()
方法中断点, 然后会发现, junit主线程结束后直接调用了System.exit(0)
public static void exit(int status) {
Runtime.getRuntime().exit(status);
}
因此, 如果多线程代码要用junit测试, 需保证主线程的执行时间比子线程长, 比如:
@Test
public void executorTest() throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(()-> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("%s---睡了3秒钟\n", Thread.currentThread().getName());
});
Thread.sleep(10_000);
}
或者使用main()
方法直截了当
网友评论