锁读写分离 ReentrantReadWriteLock
****************************
ReentrantReadWriteLock
public class ReentrantReadWriteLock
implements ReadWriteLock, java.io.Serializable {
private final ReentrantReadWriteLock.ReadLock readerLock;
private final ReentrantReadWriteLock.WriteLock writerLock;
******************************
构造函数
public ReentrantReadWriteLock() {
this(false);
} //默认为非公平锁
public ReentrantReadWriteLock(boolean fair) {
。。。。
}
*****************************
内部类ReadLock
public static class ReadLock implements Lock, java.io.Serializable {
public void lock()
public void lockInterruptibly() throws InterruptedException
public boolean tryLock()
public boolean tryLock(long timeout, TimeUnit unit)
throws InterruptedException
//获得锁
public void unlock() //释放锁
public Condition newCondition() //获得Condition对象
********************************
内部类WriteLock
public static class WriteLock implements Lock, java.io.Serializable {
public void lock()
public void lockInterruptibly()
public boolean tryLock()
public boolean tryLock(long timeout, TimeUnit unit)
//获得锁
public void unlock() //释放锁
public Condition newCondition() //获得Condition对象
*****************************
示例
class Test8{
private ReentrantReadWriteLock readWriteLock=new ReentrantReadWriteLock();
private ReentrantReadWriteLock.ReadLock readLock=readWriteLock.readLock();
private ReentrantReadWriteLock.WriteLock writeLock=readWriteLock.writeLock();
public void test(){
try{
readLock.lock();
System.out.println("获得读锁:"+Thread.currentThread().getId()+" "+System.currentTimeMillis());
Thread.sleep(10000);
}catch (Exception e){
e.printStackTrace();
}finally {
System.out.println("释放读锁:"+Thread.currentThread().getId()+" "+System.currentTimeMillis());
readLock.unlock();
}
}
public void test2(){
try{
writeLock.lock();
System.out.println("获得写锁:"+Thread.currentThread().getId()+" "+System.currentTimeMillis());
Thread.sleep(10000);
}catch (Exception e){
e.printStackTrace();
}finally {
System.out.println("释放写锁:"+Thread.currentThread().getId()+" "+System.currentTimeMillis());
writeLock.unlock();
}
}
}
class Thread8 implements Runnable{
private Test8 test8;
private boolean flag;
Thread8(Test8 test8, boolean flag){
this.test8=test8;
this.flag=flag;
}
@Override
public void run() {
if(flag){
test8.test();
}else {
test8.test2();
}
}
}
public class ThreadTest8 {
public static void main(String[] args){
Test8 test8=new Test8();
Thread8 test=new Thread8(test8,true);
Thread8 test2=new Thread8(test8,false);
Thread t1=new Thread(test);
Thread t2=new Thread(test2);
t1.start();
t2.start();
}
}
********************
控制台输出
获得读锁:14 1568853127680
释放读锁:14 1568853137717
获得写锁:15 1568853137720
释放写锁:15 1568853147722