近期有需求需要在项目中模拟高并发,研究了下网上博友的方案,写了这篇较为详细的实施方案,供以后参考。【源码在文末,即取即用】
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;
@Override
public void run() {
try {
cdl.await();
}catch (Exception e) {
e.printStackTrace();
}
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;
@Override
public void run() {
try {
cdl.await();
}catch (Exception e) {
e.printStackTrace();
}
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);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("end ... ");
}
}
|