3.1.4 读写锁

Posted anxbb

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3.1.4 读写锁相关的知识,希望对你有一定的参考价值。

一、分为两种:公平和非公平

线程 a b c d e
公平:按顺序执行:a,b,d,e 读锁 c 写锁
1.a,b 执行 c 堵塞,d,e 等待
2.a,b执行结束 c获取锁 d,e堵塞等待
3.c执行结束 d开始执行,然后在唤醒e

非公平:
1,2步骤相同
3,c执行结束的时候,新来个线程 f读锁,在d没有唤醒的情况下,会获取读锁,然后在唤醒d,e




package 第三章.读写锁;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
* Created by zzq on 2018/1/23.
*/
public class WebTestReadAndWriteLock {
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public static void main(String[] args) {
final WebTestReadAndWriteLock lock = new WebTestReadAndWriteLock();
// 建N个线程,同时读
ExecutorService service = Executors.newCachedThreadPool();
service.execute(new Runnable() {
public void run() {
lock.readFile(Thread.currentThread());
}
});
service.execute(new Runnable() {
public void run() {
lock.readFile(Thread.currentThread());
}
});
// 建N个线程,同时写
ExecutorService service1 = Executors.newCachedThreadPool();
service1.execute(new Runnable() {
public void run() {
lock.writeFile(Thread.currentThread());
}
});
service.execute(new Runnable() {
public void run() {
lock.readFile(Thread.currentThread());
}
});
service.execute(new Runnable() {
public void run() {
lock.readFile(Thread.currentThread());
}
});
service1.execute(new Runnable() {
public void run() {
lock.writeFile(Thread.currentThread());
}
});
}
// 读操作
public void readFile(Thread thread){
lock.readLock().lock();
boolean readLock = lock.isWriteLocked();
if(!readLock){
System.out.println("当前为读锁!");
}
try{
for(int i=0; i<5; i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(thread.getName() + ":正在进行读操作……");
}
System.out.println(thread.getName() + ":读操作完毕!");
}finally{
System.out.println("释放读锁!");
lock.readLock().unlock();
}
}
// 写操作
public void writeFile(Thread thread){
lock.writeLock().lock();
boolean writeLock = lock.isWriteLocked();
if(writeLock){
System.out.println("当前为写锁!");
}
try{
for(int i=0; i<5; i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(thread.getName() + ":正在进行写操作……");
}
System.out.println(thread.getName() + ":写操作完毕!");
}finally{
System.out.println("释放写锁!");
lock.writeLock().unlock();
}
}
}

以上是关于3.1.4 读写锁的主要内容,如果未能解决你的问题,请参考以下文章

java中ReentrantReadWriteLock读写锁的使用

互斥锁自旋锁读写锁和条件变量

ReentrantReadWriteLock场景应用

读写锁ReentrantReadWriteLock源代码浅析

锁,同步,可重入锁,读写锁(转)

我写的由 GCD 代码支持的读写器锁导致并行测试中的死锁