package com.imooc.demo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; public class MapExample { private static final Logger log = LoggerFactory.getLogger(MapExample.class); private static Map<Integer, Integer> map = new HashMap<>(); private static int threadNum = 1; private static int clientNum = 5000; public static void main(String[] args) { ExecutorService exec = Executors.newCachedThreadPool(); final Semaphore semaphore = new Semaphore(threadNum); for (int index = 0; index < clientNum; index++) { final int threadNum = index; exec.execute(() -> { try { semaphore.acquire(); func(threadNum); semaphore.release(); } catch (Exception e) { log.error("exception", e); } }); } exec.shutdown(); log.info("size:{}", map.size()); } public static void func(int threadNum) { map.put(threadNum, threadNum); } }
private static int threadNum = 1;
代码中将上面这行代码的值改为1之后,程序运行的结果还是小于5000,这是什么原因?
相关分类