• @Junit不支持多线程得测试


    问题: 在一次学习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

          

  • 相关阅读:
    8.1.1 播放合成声音
    CSS 用伪类 :after 选择器清除浮动
    javascript 拖拽
    javascript 回到顶端
    用 console.time()和 console.timeEnd() 测试你的 javascript 代码执行效率
    【风马一族_代码英语】代码英语之五
    【风马一族_代码英语】代码英语之四
    【风马一族_代码英语】代码英语之三
    【风马一族_Android】第4章Android常用基本控件
    【风马一族_日常灵感】在美国得到的人生感悟
  • 原文地址:https://www.cnblogs.com/wei-cy/p/13889366.html
Copyright © 2020-2023  润新知