JUnit单元测试方法不输出
在JUnit的@Test方法中启用多线程,新启动的线程会随着@Test主线程的死亡而不输出
解决方法
- 1. 在@Test方法中每创建一个线程,就join一下,这样我们新建的线程不死亡,Test主线程也不会死亡
- 2. 让主线程睡眠一会,等待其它线程结束后本线程在结束
- 3. 使用CountLatch等同步器同步一下,让主线程等其它线程结束后在结束
- 其它方法,总之就是让@Test的线程等待我们新建的线程运行结束后再结束
方法1 Thread.join()
@Test
public void testMultiThread(){
Thread thread = new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(3);
System.out.println("子线程执行完毕");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("@Test线程执行完毕");
}
输出: 子线程执行完毕
@Test线程执行完毕
可以看到Test线程会在子线程执行完之后再结束。如果有多个子线程,就让每个子线程都join一下,这样Test线程就会等待每一个子线程结束后再结束。
方法2 线程睡眠
@Test
public void testMultiThread(){
Thread thread = new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(1);
System.out.println("子线程执行完毕");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread.start();
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("@Test线程执行完毕");
}
输出:子线程执行完毕
@Test线程执行完毕
方法3 CountLatch
@Test
public void testMultiThread(){
CountDownLatch countDownLatch = new CountDownLatch(2);
Thread thread = new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(1);
System.out.println("子线程1执行完毕");
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread thread2 = new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(2);
System.out.println("子线程2执行完毕");
countDownLatch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread.start();
thread2.start();
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("@Test线程执行完毕");
}
输出:子线程1执行完毕
子线程2执行完毕
@Test线程执行完毕