【思考】并发测试模拟
线上程序出现莫名其妙的问题,最终定位为aes加密工具并发下会有问题。 在公司的并发测试平台上测试,果不其然,最终解决问题。
问题解决之余,自己想简单写一个并发测试的小代码,动手!
package com.yaochow.demo;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class TestPlatform {
public static int clientTotal = 10000;//访问数
public static int threadTotal = 4;//线程数
public static int count = 0;
@Test
public void test() throws InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(threadTotal);
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
for (int i = 0; i < clientTotal; i++) {
executorService.execute(() -> {
try {
semaphore.acquire();
add();
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
System.out.println(count);
}
private static void add() {
count++;
}
}
结果:
9998
在add方法加上同步后,结果正常(10000)。
以上。