ReentrantReadWriteLock
ReentrantReadWriteLock//读写锁, 只能单线程写,允许多线程读
ReadWriteLock
读-读可以共存!
读-写不能共存!
写-写不能共存!
package Lock;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/** ReentrantReadWriteLock//读写锁, 只能单线程写,允许多线程读
* @author liu
*/
public class ReadWriteLockA {
public static void main(String[] args) {
MyCacheLock myCacheLock = new MyCacheLock();
for (int i = 1; i <= 5; i++) {
int finalI = i;
new Thread(() -> {
myCacheLock.writer(finalI,finalI);
}, String.valueOf(i)).start();
}
for (int i = 1; i <= 5; i++) {
int finalI = i;
new Thread(() -> {
myCacheLock.read(finalI);
}, String.valueOf(i)).start();
}
}
}
class MyCacheLock {
private volatile Map<Integer, Object> map = new HashMap<>();
//读写锁, 只能单线程写,允许多线程读
private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
public void writer(Integer key, Object value) {
try {
readWriteLock.writeLock().lock();
System.out.println(Thread.currentThread().getName() + "写入" + key);
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "写入OK");
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.writeLock().unlock();
}
}
public void read(Integer key) {
try {
readWriteLock.readLock().lock();
System.out.println(Thread.currentThread().getName() + "读取" + key);
map.get(key);
TimeUnit.SECONDS.sleep(1);
System.out.println(Thread.currentThread().getName() + "读取OK");
} catch (Exception e) {
e.printStackTrace();
} finally {
readWriteLock.readLock().unlock();
}
}
}