读写锁

使用

public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MapCatch mapCatch = new MapCatch();
        for (int i = 0; i < 100; i++) {
            final int value = i;
            new Thread(() -> {
                mapCatch.put("" + value, "" + value);
            }).start();
        }
<pre><code>    for (int i = 0; i &lt; 100; i++) {
        final int value = i;
        new Thread(() -&gt; {
            mapCatch.get("" + value);
        }).start();
    }
}

}

class MapCatch { private ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private Map<String, String> map = new HashMap<>();

public void put(String key, String value) {
    readWriteLock.writeLock().lock();
    try {
        System.out.println(Thread.currentThread().getName() + "开始写入");
        map.put(key, value);
        System.out.println(Thread.currentThread().getName() + "写入完毕");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        readWriteLock.writeLock().unlock();
    }

}

public Object get(String key) {
    readWriteLock.readLock().lock();
    Object object = null;
    try {
        System.out.println(Thread.currentThread().getName() + "开始读取");
        object = map.get(key);
        System.out.println(Thread.currentThread().getName() + "读取完毕");
    } finally {
        readWriteLock.readLock().unlock();
    }
    return object;
}

}