码迷,mamicode.com
首页 > 编程语言 > 详细

java hashmap分段锁实现

时间:2020-06-20 23:48:24      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:imp   get   dex   void   分段   new   art   catch   inter   

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分段锁实现

标签:imp   get   dex   void   分段   new   art   catch   inter   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!