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();
}
}