ReadWriteLock 使用实例

首先来讨论ReadWriteLock 类的使用场景,记住一句话:在多线程,“读多写少”的场景就推荐使用,可以提高线程的性能。下面是一个实例:

import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class WriteReadMap<K, V> {
	private final Map<K,V> map;
	private final ReadWriteLock lock = new ReentrantReadWriteLock();
	private final Lock r = lock.readLock();
	private final Lock w = lock.writeLock();
	
	public WriteReadMap(Map<K, V> map) {
		this.map = map;
	}
	
	public V put(K key,V value) {
		w.lock();
		try {
			return  map.put(key, value);
		} finally {
			w.unlock();
		}
	}
	
	public V get(Object key) {
		r.lock();
		try {
			return map.get(key);
		} finally {
			r.unlock();
		}
	}
}

 

你可能感兴趣的:(ReadWriteLock)