读写锁的使用

阅读更多
package concurrent;

import java.util.Random;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

/**
 *1、readLock可重入;
 *2、writeLock必须等待所有的readLock释放后才可进入;
 *3、writeLock范围内,readLock不可进入
 */
public class ReadWriteLockTest {

	private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

	private ReadLock readLock = readWriteLock.readLock();

	private WriteLock writeLock = readWriteLock.writeLock();

	private String shareData = "寂寞等待中。。。";

	public ReadWriteLockTest() {
	}

	public void write(String str) {		
		writeLock.lock();//可用tryLock()干点其他事
//		if(!writeLock.tryLock()){
//			System.err.println("读锁数量:"+readWriteLock.getReadLockCount());
//			return;
//		}
		System.err.println("ThreadName:" + Thread.currentThread().getName() + "    locking...");
		try {
			shareData = str;
			System.err.println("ThreadName:" + Thread.currentThread().getName() + "   修改为:" + str);
			Thread.sleep(50);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			System.err.println("ThreadName:" + Thread.currentThread().getName() + "    unlock...");
			writeLock.unlock();
		}
	}

	public String read() {
		readLock.lock();
		System.out.println("ThreadName:" + Thread.currentThread().getName() + "    lock...");
		try {
			System.out.println("ThreadName:" + Thread.currentThread().getName() + "   获取为:" + shareData);
			Thread.sleep(50);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			readLock.unlock();
			System.out.println("ThreadName:" + Thread.currentThread().getName() + "    unlock...");
		}
		return shareData;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		final ReadWriteLockTest shareData = new ReadWriteLockTest();

		for (int i = 0; i < 5; i++) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					shareData.read();
				}
			}, "get Thread-" + i).start();
		}
		
		for (int i = 0; i < 10; i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					shareData.write(new Random().nextLong() + "");
				}
			}, "write Thread-" + i).start();

		}
	}
}

你可能感兴趣的:(java,ReadLock,WriteLock)