读写锁---ReentrantReadWriteLock
读写锁---ReentrantReadWriteLock
可重复读写锁:
可以更加细粒度控制读和写的锁情况。
读锁可以多线程一起读,写只能一个一个按顺序写,可以进一步提高代码效率
独占锁即写锁
共享锁即读锁
下面代码可以把注释解开运行下看下效果
package com.example.juc;
import java.util.HashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class TestReadWriteLock {
public static void main(String[] args) {
// MyCache myCache = new MyCache();
MyCacheLock myCache = new MyCacheLock();
for (int i = 0; i < 6; i++) {
final int temp = i;
new Thread(() -> {
myCache.put(String.valueOf(temp), String.valueOf(temp));
}, String.valueOf(i)).start();
}
for (int i = 0; i < 6; i++) {
final int temp = i;
new Thread(() -> {
myCache.get(String.valueOf(temp));
}, String.valueOf(i)).start();
}
}
}
class MyCacheLock {
private HashMap map = new HashMap<String, String>();
private ReadWriteLock lock = new ReentrantReadWriteLock();
public void get(String key) {
lock.readLock().lock();
try {
System.out.println("开始获取" + Thread.currentThread().getName());
map.get(key);
System.out.println("获取完毕" + Thread.currentThread().getName());
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.readLock().unlock();
}
}
public void put(String key, String value) {
lock.writeLock().lock();
try {
System.out.println("开始写入" + Thread.currentThread().getName());
map.put(key, value);
System.out.println("写入完毕" + Thread.currentThread().getName());
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.writeLock().unlock();
}
}
}
class MyCache {
private HashMap map = new HashMap<String, String>();
public void get(String key) {
System.out.println("开始获取" + Thread.currentThread().getName());
map.get(key);
System.out.println("获取完毕" + Thread.currentThread().getName());
}
public void put(String key, String value) {
System.out.println("开始写入" + Thread.currentThread().getName());
map.put(key, value);
System.out.println("写入完毕" + Thread.currentThread().getName());
}
}