ReadWriteLock 又称为共享锁,的读写分离锁,内部分为读锁和写锁
关于 A 和 B 线程,读和写的关系
A 读 — B 读:不互斥、不阻塞
A 读 — B 写:互斥,互相阻塞
A 写 — B 写:互斥,互相阻塞
用法:非常简单,和 ReentrantLock 一样
public class TestReadWriteLock {
// 实例化读写锁
private static final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private static final Lock readLock = readWriteLock.readLock();
private static final Lock writeLock = readWriteLock.writeLock();
private static int count = 0;
static class ReadThread implements Runnable {
@Override
public void run() {
readLock.lock();
try {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " 进来了: count = " + count);
Thread.sleep(2000);
} catch (Exception e) {
} finally {
readLock.unlock();
}
}
}
static class WriteThread implements Runnable {
@Override
public void run() {
writeLock.lock();
try {
System.out.println(System.currentTimeMillis() + " : " + Thread.currentThread().getName() + " 进来了: count = " + (++count));
Thread.sleep(2000);
} catch (Exception e) {
} finally {
writeLock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
System.out.println("======开始测试写锁======");
Thread[] threads = new Thread[10];
ReadThread read = new ReadThread();
for (int i = 0; i < threads.length; i++) threads[i] = new Thread(read, "线程 " + i);
for (int i = 0; i < threads.length; i++) threads[i].start();
for (int i = 0; i < threads.length; i++) threads[i].join();
System.out.println("\n======开始测试读锁======");
WriteThread write = new WriteThread();
for (int i = 0; i < threads.length; i++) threads[i] = new Thread(write, "线程 " + i);
for (int i = 0; i < threads.length; i++) threads[i].start();
for (int i = 0; i < threads.length; i++) threads[i].join();
}
}
输出结果,读锁相当于没有锁
======开始测试写锁======
1537876265912 : 线程 0 进来了: count = 0
1537876265912 : 线程 1 进来了: count = 0
1537876265912 : 线程 2 进来了: count = 0
1537876265912 : 线程 3 进来了: count = 0
1537876265913 : 线程 5 进来了: count = 0
1537876265912 : 线程 4 进来了: count = 0
1537876265913 : 线程 7 进来了: count = 0
1537876265913 : 线程 8 进来了: count = 0
1537876265913 : 线程 6 进来了: count = 0
1537876265913 : 线程 9 进来了: count = 0
======开始测试读锁======
1537876267915 : 线程 0 进来了: count = 1
1537876269916 : 线程 2 进来了: count = 2
1537876271916 : 线程 1 进来了: count = 3
1537876273917 : 线程 4 进来了: count = 4
1537876275918 : 线程 3 进来了: count = 5
1537876277918 : 线程 5 进来了: count = 6
1537876279919 : 线程 6 进来了: count = 7
1537876281919 : 线程 7 进来了: count = 8
1537876283920 : 线程 8 进来了: count = 9
1537876285920 : 线程 9 进来了: count = 10