当前位置: 代码迷 >> 综合 >> Java 读写锁
  详细解决方案

Java 读写锁

热度:18   发布时间:2024-01-31 12:48:12.0
package com.study.demo;import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;/*** 资源类*/
class MyCache{private volatile HashMap<String,Object> map = new HashMap<>();private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();public void put(String key,Object object){rwLock.writeLock().lock();try {System.out.println(Thread.currentThread().getName()+"\t 正在写入:"+key);try {TimeUnit.MILLISECONDS.sleep(300);}catch (InterruptedException e){e.printStackTrace();}map.put(key, object);System.out.println(Thread.currentThread().getName()+"\t 写入完成:"+key);} catch (Exception e) {e.printStackTrace();} finally {rwLock.writeLock().unlock();}}public void get(String key){rwLock.readLock().lock();try {System.out.println(Thread.currentThread().getName()+"\t 正在读取");try {TimeUnit.MILLISECONDS.sleep(300);}catch (InterruptedException e){e.printStackTrace();}Object result = map.get(key);System.out.println(Thread.currentThread().getName()+"\t 读取完成"+result);} catch (Exception e) {e.printStackTrace();} finally {rwLock.readLock().unlock();}}
}/*** 读写锁* 读-读能共存* 读-写不能共存* 写-写 不能共存* 写操作 原子+独占*/
public class ReadWriteLock {public static void main(String[] args) {MyCache myCache = new MyCache();for (int i = 0; i < 5; i++) {final int temp = i;new Thread(()->{myCache.put(temp+"",temp+"");},String.valueOf(i)).start();}for (int i = 0; i < 5; i++) {final int temp = i;new Thread(()->{myCache.get(temp+"");},String.valueOf(i)).start();}}
}