001--【测试】并发测试类编写

1、写作背景

项目一定不仅仅是CRUD,更多的工作应该是放在测试,性能,稳定上面


2、参考网址

3、进行工具类编写

项目功能编写完成之后,写测试用例,进行性能测试(很有必要)

@RunWith(SpringRunner.class)
@SpringBootTest
public class SeckillApplicationTests {

    public static final String SKU = "iPhone7";
    public static int UserCount = 5;
    public static int UserBuyCount = 3;
    public static AtomicInteger userSuccessCount = new AtomicInteger();
    public static AtomicInteger stackSuccessCount = new AtomicInteger();

    @Resource
    KillService killService;
    @Test
    public void contextLoads() {
        boolean flag = killService.updateGoodsCount(1, SKU);
        System.out.println("------------------数据更新成功:"+flag);
    }

    @Test
    // thread.join()等待线程组执行结束
    public void contextLoadsThread() throws InterruptedException {
        for (int i = 0; i < UserCount; i++) {
            Thread task = new Thread() {
                @Override
                public void run() {
                    doSomeThing();
                }
            };
            task.start();
            task.join();
        }
        System.out.println("------------------购买成功人数:"+userSuccessCount);
        System.out.println("------------------购买成功商品:"+stackSuccessCount);
    }

    // 核心业务操作
    public void doSomeThing() {
        if (killService.updateGoodsCount(UserBuyCount, SKU)){
            System.out.println("------------------数据更新成功");
            userSuccessCount.incrementAndGet();//购买成功用户加一
            stackSuccessCount.addAndGet(UserBuyCount);//购买成功商品
        }else {
            System.out.println("------------------数据更新失败");
        }
    }
}
  • 测试类编写最好避免以下:CountDownLatch、Semaphore和CyclicBarrier(因为没有办法判断当前线程是否已经完成任务处理)
    public void contextLoadsThread() throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
//        final Semaphore semaphore = new Semaphore(UserCount);
        final CountDownLatch countDownLatch = new CountDownLatch(UserCount);
        for (int i = 0; i < UserCount ; i++) {
            executorService.execute(() -> {
                try {
//                    semaphore.acquire();
                    doSomeThing();
//                    semaphore.release();
                } catch (Exception e) {
                    System.out.println("exception:"+e);
                }
                countDownLatch.countDown();
            });
        }
//        countDownLatch.await();
        executorService.shutdown();
        // 要稍微等一下,线程可能没有执行完成(没有接收异步任务)
        Thread.sleep(1000);
        System.out.println("-------------->任务执行完成");
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值