缓存是ConcurrentHashMap怎么做给个例子?

iiii)ConcurrentHashMap:

马克-to-win:ConcurrentHashMap是java1.5的新特性。HashTable在并发环境下效率低的原因: HashTable就一把锁,所有线程竞争。ConcurrentHashMap里面有很多锁,就像数据库里的行级锁一样。改这行,锁这行,不影响别的 行。最重要的是:一个线程添加(put)元素,同时另一个线程读数据不会引起ConcurrentModificationException异常。读写 可以同时进行,只不过读的有可能不是最新数据。马克-to-win:所以如果需要原子操作时,还得手动加锁。所以我们前面学的锁的理论,照样适用。(见下面的例子)

例 2.2.2.1

package com;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
class MulThreMarkToWin extends Thread {
    Map map;
    public MulThreMarkToWin(Map map) {
        this.map = map;
    }
    public void run() {
        for (int i = 1; i <= 30; i++) {

            System.out.println("第一个线程要睡觉");
            try {
                Thread.sleep(3);
                System.out.println("第一个线程刚睡完");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class MulThreMarkToWinInsert extends Thread {
    Map map;
    public MulThreMarkToWinInsert(Map map) {
        this.map = map;
    }
    public void run() {
        for (int i = 1; i <= 30; i++) {
            map.put("kkk" + i, "vvv" + i);
            System.out.println("添加了一对 " + i);
            System.out.println("第二个线程要睡觉觉睡得短,所以很两个线程执行顺序完全不可控,不睡觉就不能混着执行了");
            try {
                Thread.sleep(3);
                System.out.println("第二个线程刚睡完");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class TestConcurBuy_MarkToWin {
    public static void main(String[] args) {
        Map map = new ConcurrentHashMap();
/*下面三种集合都会报ConcurrentModificationException异常*/
//        Map map = Collections.synchronizedMap(new HashMap());
//        Map map = new HashMap();
//        Map map = new Hashtable();
        Thread t1 = new MulThreMarkToWin(map);
        Thread t2 = new MulThreMarkToWinInsert(map);
        t1.start();
        t2.start();
    }
}


更多内容请见原文,文章转载自:https://blog.csdn.net/qq_44638460/article/details/104145821

posted @ 2022-03-19 20:36  malala  阅读(83)  评论(0编辑  收藏  举报