public class ConcurrentHashMapExample2 {
//请求总数
public static int clientTotal = 5000;
//同时并发执行的线程数
public static int threadTotal = 200;
private static Map<String,Integer> map = new ConcurrentHashMap<>();
public static void main(String[] args) throws Exception{
ExecutorService executorService = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(threadTotal);
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
final String key = "key";
for (int i=0;i<clientTotal;i++){
executorService.execute(() ->{
try {
semaphore.acquire();
add(key);
semaphore.release();
} catch (Exception e) {
log.error("exception",e);
}
countDownLatch.countDown();
});
}
countDownLatch.await();//保证减少到0
executorService.shutdown();
log.info("size:{}", map.get(key));
}
private static void add(String key){
Integer value = map.get(key);
if (value == null) {
map.put(key, 1);
} else {
map.put(key, value + 1);
}
}
}
我能知道线程不安全的原因是判空的地方有问题,但是应该怎么改才能变成线程安全的,除了在方法上加synchronized?