直接贴上学习的测试代码:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class func {
private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
private Lock wl = rwl.writeLock();
private Lock rl = rwl.readLock();
public void ww() throws InterruptedException {
wl.lock();
Thread.sleep(2000);
System.out.println("write here");
wl.unlock();
}
public void rr() throws InterruptedException {
rl.lock();
Thread.sleep(3000);
System.out.println("read here");
rl.unlock();
}
}
public class test {
public static void main(String[] args) {
final func f = new func();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
f.rr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
try {
f.rr();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
try {
f.ww();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
thread2.start();
thread3.start();
}
}
从运行的代码结果可以看出,线程在执行读锁的时候互相不会阻塞,但是读锁和写锁之间会相互被阻塞,同时读锁和读锁之间也是会相互阻塞的。
简单点说就是:A君在写文章,B君和C君只能等待,等A写完了B和C才能看,如果B和C都在看文章,A君就必须等待他们看完才能继续写文章。