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方法用于处理业务逻辑
@Override
public void run() {
try {
cdl.await();
}catch (Exception e) {
e.printStackTrace();
}
// todo 业务逻辑...
System.out.println("now no = " + no);
}
}
3.测试高并发
@Test
public 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 = 1 now no = 0 now no = 2 now no = 4 now no = 3 now no = 5 now no = 6 now no = 7 now no = 8 now no = 9 end ...
说明线程间互不影响,模拟成功。
完整代码:
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方法用于处理业务逻辑
@Override
public void run() {
try {
cdl.await();
}catch (Exception e) {
e.printStackTrace();
}
// todo 业务逻辑...
System.out.println("now no = " + no);
}
}
@Test
public 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 ... ");
}
}



