还在用第三方压测吗,几行Java代码就能实现一个压测工具。
很简单,就是使用CountDownLatch控制线程同时执行,直接上代码:
public static void main(String[] args) {
//并发数
int CONCURRENT_NUM = 100;
//用来控制等待子线程全部创建完成再执行
CountDownLatch countDownLatch = new CountDownLatch(CONCURRENT_NUM);
for (int i = 0; i < CONCURRENT_NUM; i++) {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
countDownLatch.countDown();//当前线程调用此方法,则计数减一
countDownLatch.await();//阻塞当前线程,直到计数器的值为0
//todo 压测访问
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
new Thread(runnable).start();;
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}