// 利用ConcurrentHashMap computeIfAbsent 的 线程安全操作,来做初始化时其他必要的操作。 public static void main(String[] args) throws InterruptedException { ConcurrentHashMap<String, IntX3> map = new ConcurrentHashMap<>(); int threadCount = 10; AtomicInteger count = new AtomicInteger(0); CountDownLatch latch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; i++) { new Thread(new Runnable() { int index = 0; Runnable setIndex(int index) { this.index = index; return this; } @Override public void run() { for (int j = 0; j < 100; j++) { String key = "" + j; int v = j; map.computeIfAbsent(key, e -> { var x3 = new IntX3(index, v, 1); count.addAndGet(1); return x3; }); } latch.countDown(); } }.setIndex(i)).start(); } latch.await(); var ite = map.entrySet().iterator(); while (ite.hasNext()) { var e = ite.next(); System.err.println(e.getKey() + " == " + e.getValue()); } System.err.println(count.get()); }
ConcurrentHashMap
最新推荐文章于 2021-12-30 15:35:20 发布