Maven CyclicBarrier栅栏,高并发测试工具类

 

package com.dayuanit.test;

import com.dayuanit.service.CardService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;

public class TransferTest {
    //线程个数为100个,可以根据需要修改大小
    public static final int thread_num = 100;
   
    public static CyclicBarrier barrier = new CyclicBarrier(thread_num);
    public static CountDownLatch downLatch = new CountDownLatch(thread_num);
    //用于解决++ --的线程安全问题
    public static AtomicInteger errorNum = new AtomicInteger(0);
    public static AtomicInteger successNum = new AtomicInteger(0);

    public static void main(String[] args) throws Exception{
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"classpath:applicationContext.xml"});
        CardService cardService = context.getBean(CardService.class);

        TransferRunnable transferRunnable = new TransferRunnable(cardService);
        //循环创建100个线程
        for (int i=0; i<thread_num; i++) {
            new Thread(transferRunnable).start();
        }

        //栅栏等待所有的线程执行完毕
        downLatch.await();

        System.out.println("成功的个数" + TransferTest.successNum);
        System.out.println("失败的个数" + TransferTest.errorNum);
    }
}

class TransferRunnable implements Runnable {

    private CardService cardService;

    public TransferRunnable(CardService cardService) {
        this.cardService = cardService;
    }

    @Override
    public void run() {
        try {
            //等待所有线程到达后,开始一起执行
            TransferTest.barrier.await();
            //需要高并发测试的方法
            cardService.transfer("6002", "6005", "10", 1);
            TransferTest.successNum.addAndGet(1);
        } catch (Exception e) {
            e.printStackTrace();
            TransferTest.errorNum.addAndGet(1);
        }

        TransferTest.downLatch.countDown();
    }
}

 

转载于:https://my.oschina.net/u/3446892/blog/1649026

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值