Java多线程之《读写锁》

    xiaoxiao2024-03-24  136

    读写锁实现缓存示例:

    package concurrent; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Desc: 缓存示例,读写锁实现 * Creator: pengweixiang * Date: 2019-04-21 */ public class Cache { private static Map<String, String> map = new HashMap<>(); private static ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); private static Lock r = rwl.readLock(); private static Lock w = rwl.writeLock(); /** * 获取对应key的值 * @param key key * @return value */ public static String get(String key) { r.lock(); try { return map.get(key); } finally { r.unlock(); } } /** * 设置key对应的新值,并返回旧的值 * @param key key * @param value newValue * @return oldValue */ public static String put(String key, String value) { w.lock(); try { return map.put(key, value); } finally { w.unlock(); } } /** * 清空缓存的所有值 */ public static void clearCache() { w.lock(); try { map.clear(); } finally { w.unlock(); } } }

    测试代码:

    package concurrent; import org.junit.Test; /** * Desc: 读写锁Cache测试类 * Creator: pengweixiang * Date: 2019-04-21 */ public class CacheTest { @Test public void test() { for (int i = 0; i < 2; i++) { String threadName = "thread" + i; ReadTask readTask = new ReadTask(threadName); WriteTask writeTask = new WriteTask(threadName); readTask.setDaemon(true); writeTask.setDaemon(true); writeTask.start(); readTask.start(); } TimeUtils.sleep(20); } private static class ReadTask extends Thread { private String threadName; public ReadTask(String name) { super(name); threadName = name; } @Override public void run() { while (true) { String value = (String) Cache.get(threadName); System.out.println(Thread.currentThread().getName() + ", read value: " + value); TimeUtils.sleep(1); } } } private static class WriteTask extends Thread { private String threadName; public WriteTask(String name) { super(name); threadName = name; } @Override public void run() { while (true) { String value = (String) Cache.put(threadName, TimeUtils.getCurrentTime()); System.out.println(Thread.currentThread().getName() + ", write value: " + value); TimeUtils.sleep(1); } } } }

    github地址:https://github.com/thinkerpeng/Java-Concurrent

    最新回复(0)