近期有需求需要在项目中模拟高并发,研究了下网上博友的方案,写了这篇较为详细的实施方案,供以后参考。【源码在文末,即取即用】
1.定义高并发请求数与倒计时器
新建测试类HighConcurrentTest.java, 定义变量:
// 并发请求数private static final int threadNum =10;// 倒计时器private CountDownLatch cdl =new CountDownLatch(threadNum);
2.设计实现Runable接口的用户请求类(在HighConcurrentTest类内定义)
public class UserRequest implements Runnable {public UserRequest() {}public UserRequest(int no) {this.no = no;}public int no;// 重写run方法用于处理业务逻辑@Overridepublic void run() {try {cdl.await();}catch (Exception e) {e.printStackTrace();}// todo 业务逻辑...System.out.println("now no = " + no);}}
3.测试高并发
@Testpublic void testConcurrent(){System.out.println("start ... ");for (int i =0; i< threadNum; i++) {new Thread(new UserRequest(i)).start();// 倒计时计数cdl.countDown();}try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("end ... ");}
执行后可发现日志顺序为:
start ... now no = 1now no = 0now no = 2now no = 4now no = 3now no = 5now no = 6now no = 7now no = 8now no = 9end ...
说明线程间互不影响,模拟成功。
完整代码:
package xyz.dongzhensong.junitlearn.util;import org.junit.Test;import java.util.concurrent.CountDownLatch;public class HighConcurrentTest {// 并发请求数private static final int threadNum =10;// 倒计时器private CountDownLatch cdl =new CountDownLatch(threadNum);public class UserRequest implements Runnable {public UserRequest() {}public UserRequest(int no) {this.no = no;}public int no;// 重写run方法用于处理业务逻辑@Overridepublic void run() {try {cdl.await();}catch (Exception e) {e.printStackTrace();}// todo 业务逻辑...System.out.println("now no = " + no);}}@Testpublic void testConcurrent(){System.out.println("start ... ");for (int i =0; i< threadNum; i++) {new Thread(new UserRequest(i)).start();// 倒计时计数cdl.countDown();}try {Thread.sleep(5000);// 如线程内操作执行脚本,可先阻塞线程,等待子线程执行完成// Thread.currentThread().join();} catch (InterruptedException e) {e.printStackTrace();}System.out.println("end ... ");}}
如果觉得《【JAVA单元测试】单元测试模拟高并发操作》对你有帮助,请点赞、收藏,并留下你的观点哦!