当单元测试中存在线程等待情况的处理

使用join()进行处理

示例

public class JunitConcurrentTest {

	@Test
	public void concurrentCase() {
		System.out.println(Thread.currentThread().getName() + " concurrentCase...");
		Thread t1 = new Thread(new Runnable() {

			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName() + " run....");
				ThreadUtil.sleep(15, TimeUnit.SECONDS);
				System.out.println(Thread.currentThread().getName() + " run end....");
			}
		});
		t1.setName("t1");
		Thread t2 = new Thread(new Runnable() {

			@Override
			public void run() {
				System.out.println(Thread.currentThread().getName() + " run....");
				ThreadUtil.sleep(10, TimeUnit.SECONDS);
				System.out.println(Thread.currentThread().getName() + " run end....");
			}
		});
		t2.setName("t2");
		System.out.println(Thread.currentThread().getName() + " start1....");
		t1.start();
		System.out.println(Thread.currentThread().getName() + " start2....");
		t2.start();
		try {
			t1.join();
			t2.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().getName() + " end....");
	}

}

参考

  1. Junit单元测试多线程的问题