多线程 : 读写锁实现缓存系统

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class CacheSystem {

	public static void main(String[] args) {

		// 测试缓存器
		final CacheSystem cache = new CacheSystem();

		for (int i = 0; i < 3; i++) {
			new Thread(new Runnable() {
				public void run() {
					while (true) {
						int num = new Random().nextInt(10);
						String key = num + "";
						Object result = cache.get(key);
						System.out.println(Thread.currentThread().getName() + "正在查询:" + key);
						try {
							Thread.sleep(num * 1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						System.out.println(Thread.currentThread().getName() + "查询结果为:" + key + "=" + result);
					}
				}
			}).start();
		}
	}

	// 内部存储器
	private Map<String, Object> cache = new HashMap<String, Object>();

	private ReadWriteLock rwl = new ReentrantReadWriteLock();

	public Object get(String key) {
		// 上读锁
		rwl.readLock().lock();
		Object value = cache.get(key);
		if (value == null) {
			// 释放读锁,加写锁
			rwl.readLock().unlock();
			rwl.writeLock().lock();
			if (value == null) {
				value = "value";
				cache.put(key, value);
			}
			// 还原读锁,释放写锁
			rwl.readLock().lock();
			rwl.writeLock().unlock();
		}
		// 释放读锁
		rwl.readLock().unlock();
		return value;
	}
}

经验分享 程序员 微信小程序 职场和发展