一、分为两种:公平和非公平
线程 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();
}
}
}