读写锁ReentrantReadWriteLock:读读共享,读写互斥,写写互斥

  JDK1.5以后,提供了读写锁ReentrantReadWriteLock,读写锁维护了一对锁,一个读锁,一个写锁,经过分离读锁和写锁,使得并发性相比通常的排他锁有了很大提高。在读多写少的状况下,读写锁可以提供比排他锁更好的并发性和吞吐量。java

  从源码中能够看出,读写锁中一样依赖队列同步器Sync(AQS)实现同步功能,而读写状态就是其同步器的同步状态。下面从例子中来讲明:读读共享,读写互斥,写写互斥。并发

代码以下:线程

public class ReentrantWriteReadLockTest {
	ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
	ReadLock readLock = lock.readLock();
	WriteLock writeLock = lock.writeLock();
	
	public void read(){
		try {
			readLock.lock();
			System.out.println("线程"+Thread.currentThread().getName()+"进入。。。");
			Thread.sleep(3000);
			System.out.println("线程"+Thread.currentThread().getName()+"退出。。。");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			readLock.unlock();
		}
	}
	
	public void write(){
		try {
			writeLock.lock();
			System.out.println("线程"+Thread.currentThread().getName()+"进入。。。");
			Thread.sleep(3000);
			System.out.println("线程"+Thread.currentThread().getName()+"退出。。。");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally{
			writeLock.unlock();
		}
	}
	

	public static void main(String[] args) {
		final ReentrantWriteReadLockTest wr = new ReentrantWriteReadLockTest();
		Thread t1 = new Thread(new Runnable() {
			public void run() {
				wr.read();
			}
		}, "t1");
		Thread t2 = new Thread(new Runnable() {
			public void run() {
				wr.read();
			}
		}, "t2");
		Thread t3 = new Thread(new Runnable() {
			public void run() {
				wr.write();
			}
		}, "t3");
		Thread t4 = new Thread(new Runnable() {
			public void run() {
				wr.write();
			}
		}, "t4");
		
		t1.start();
		t2.start();
		//t3.start();
		//t4.start();
	}
}

当咱们启动线程t1和t2时,结果以下:code

线程t1和t2能够同时进入,说明了读读共享!blog

当咱们启动线程t2和t3时,结果以下:队列

一个线程必须等待另外一个线程退出,才能进入,说明了读写互斥!get

当咱们启动线程t3和t4时,结果以下:同步

一个线程必须等待另外一个线程退出,才能进入,说明了写写互斥!源码

以上实例说明,读写锁ReentrantReadWriteLock:读读共享,读写互斥,写写互斥!it