JUnit unit testing multi-threaded

Enabling multi-threaded @Test method in JUnit, the start of a new thread as the main thread @Test death and death! Resulting in no output
solutions
1. Each creates a thread @Test method, you join it, so that our new thread is not dead, Test main thread will not die.
2. The main thread to sleep for a while, waiting for the end of the other end of the thread in this thread
synchronization bit 3. CountLatch such as synchronizer, the main thread and other threads after the other at the end of
the other methods, in short, is to make us wait @Test thread the new thread runs after the end of the end

The third direct implementation

package com.zjm;

import com.zjm.bean.Stock;
import com.zjm.redis.RedisLock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.CountDownLatch;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ZookeeperApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestStock {
    @Autowired
    public   RedisLock redisLock;
    CountDownLatch countDownLatch = new CountDownLatch(2);
    public class StockThread implements Runnable{
        public RedisLock redisLock;
        public StockThread(RedisLock redisLock){
            this.redisLock=redisLock;
        }
        public void run(){
            redisLock.lock();
            boolean b = new Stock().reduceStock();
            redisLock.unlock();

            if (b){
                System.out.println(Thread.currentThread().getName()+":减少库存成功");
            }else{
                System.out.println(Thread.currentThread().getName()+":减少库存失败");
            }
            countDownLatch.countDown();
        }
    }

    @Test
    public void test(){
        new Thread(new StockThread(redisLock),"线程2").start();
        new Thread(new StockThread(redisLock),"线程1").start();


        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        //单元测试无法测试多线程!!!!需要借助 可以利用三方工具:GroboUtils。
//        new Thread(new StockThread(redisLock),"线程1").start();
//        new Thread(new StockThread(redisLock),"线程2").start();
/*        redisLock.lock();
        boolean b = new Stock().reduceStock();
        redisLock.unlock();
        if (b){
            System.out.println(Thread.currentThread().getName()+":减少库存成功");
        }else{
            System.out.println(Thread.currentThread().getName()+":减少库存失败");
        }*/
    }
}

 

Published 83 original articles · won praise 14 · views 60000 +

Guess you like

Origin blog.csdn.net/zhangjianming2018/article/details/104744812