java hashmap分段锁实现
Posted 光阴易逝,岂容我待
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java hashmap分段锁实现相关的知识,希望对你有一定的参考价值。
import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class TestThred03 extends Thread { private static int num = 0; private static int num1 = 0; private static HashMap<String, Integer> hashMap = new HashMap<String, Integer>(); public TestThred03() { num = 0; num1=0; hashMap.put("1", 0); hashMap.put("2", 0); hashMap.put("3", 0); hashMap.put("4", 0); hashMap.put("5", 0); } public void run() { Iterator iter = hashMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey(); Object val = entry.getValue(); if (key.equals("1") || key.equals("2")) { synchronized (this) { num++; entry.setValue(num); System.out.println(Thread.currentThread().getName()+"-num:"+num); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } else { synchronized (this) { num1++; entry.setValue(num1); System.out.println(Thread.currentThread().getName()+"-num1:"+num1); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } } public static void main(String[] args) { TestThred03 syncThread = new TestThred03(); Thread thread1 = new Thread(syncThread, "SyncThread1"); Thread thread2 = new Thread(syncThread, "SyncThread2"); thread1.start(); thread2.start(); } }
以上是关于java hashmap分段锁实现的主要内容,如果未能解决你的问题,请参考以下文章
ConcurrentHashMap的实现原理是分段锁?你Out了
ConcurrentHashMap的实现原理是分段锁?你Out了