首页 > 编程语言 > 详细

java hashmap分段锁实现

时间:2020-06-20 23:33:53      阅读:138      评论:0      收藏:0      [点我收藏+]
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分段锁实现

原文:https://www.cnblogs.com/honghong75042/p/13170853.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!