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

来源:互联网 发布:花与剑 js 编辑:程序博客网 时间:2024/06/10 20:22
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 blocke.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;}}

1 0