读写锁:核心思想实现读写分离,高并发下特别适合 读多写少的场景。
因为synchronized关键字和ReentrantLock 同一时间只能有一个线程进行访问被锁定的代码,读写锁的机制则不是,本质上分为两把锁,读锁和写锁,在读锁情况下,多个线程可以并发访问资源,只有当是写锁时只能一个一个的顺序执行。
口诀:读读共享,写写互斥,读写互斥。
代码如下:
package com.example.demo;
public class Test {
public static void main(String[] args) {
final Printer printer = new Printer();
Thread thread1 = new Thread(){
@Override
public void run() {
printer.read("thread1 read...");
printer.write("thread1 write...");
}
};
Thread thread2 = new Thread(){
@Override
public void run() {
printer.read("thread2 read...");
printer.write("thread2 write...");
}
};
thread1.start();
thread2.start();
}
}
操作类:
package com.example.demo;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Printer {
ReadWriteLock lock = new ReentrantReadWriteLock();
/**
* 读操作
* @author stone
* @date 2018-08-07
*/
public void read(String str){
lock.readLock().lock();//读锁1
try{
for (int i = 0; i < 3; i++) {
try {
System.out.println(str);
Thread.sleep(200);//暂停200ms,不释放锁,以便更好的观察输出结果
} catch (InterruptedException e) {
}
}
}finally{
lock.readLock().unlock();//解锁,要放在finnall块里面
}
}
/**
* 写操作
* @author stone
* @date 2018-08-07
*/
public void write(String str){
lock.writeLock().lock();//写锁
try{for (int i = 0; i < 3; i++) {
try {
System.out.println(str);
Thread.sleep(200);//暂停200ms,不释放锁,以便更好的观察输出结果
} catch (InterruptedException e) {
}
}
}finally{
lock.writeLock().unlock();//解锁
}
}
}
结果如下:
thread1 read...
thread2 read...
thread2 read...
thread1 read...
thread2 read...
thread1 read...
thread1 write...
thread1 write...
thread1 write...
thread2 write...
thread2 write...
thread2 write...