问题: 在一次学习mq,写单元测试得时候,发现并不支持多线程测试。如果开多个线程,主线程运行结束就结束了,并不会等待子线程执行完。
解决思路:在子线程结束前,阻塞主线程。
解决方案:
(1)让主线程休眠10s
@Test public void threadTest() throws InterruptedException { //(1)让主线程休眠10s for (int i = 0; i <5 ; i++) { new Thread(new ThreadDemo()).start(); } Thread.sleep(10000); } class ThreadDemo implements Runnable{ @Override public void run() { System.out.println("当前线程-----"+Thread.currentThread().getId()); } }
(2)使用join
@Test public void threadTest() throws InterruptedException { //(2) 将子线程加入到主线程中,这样一来就能确保子线程得逻辑先执行结束后在执行主线程 ThreadDem thread1 = new ThreadDemo(); ThreadDemo thread2 = new ThreadDemo(); thread1.start(); thread2.start(); thread1.join(); thread2.join(); } class ThreadDemo extends Thread{ @Override public void run() { for (int i = 0; i <3 ; i++) { System.out.println("当前线程-----"+Thread.currentThread().getId()); } } }
(3)使用CountDownLatch
@Test public void threadTest() throws InterruptedException { CountDownLatch latch = new CountDownLatch(2); ThreadDemo thread1 = new ThreadDemo (); ThreadDemo thread2 = new ThreadDemo(); thread1.start(); thread2.start(); latch.await(); } class ThreadDemo extends Thread{ @Override public void run() { for (int i = 0; i <3 ; i++) { System.out.println("当前线程-----"+Thread.currentThread().getId()); } } }
参考链接: (1)https://blog.csdn.net/w605283073/article/details/92016433?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522160384792219724835815719%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=160384792219724835815719&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_v2~rank_v28-1-92016433.pc_first_rank_v2_rank_v28&utm_term=Test%E4%B8%8D%E6%94%AF%E6%8C%81%E5%A4%9A%E7%BA%BF%E7%A8%8B&spm=1018.2118.3001.4187