使用 ReentrantReadWriteLock

在上一篇文章中介绍了ReentrantLock,修改为ArrayList为线程安全的方法,但是效率上如果用ReentrantReadWriteLock还是有提高的。对于写操作调用ReentrantReadWriteLock.WriteLock writeLock()方法,对于读操作调用ReentrantReadWriteLock.ReadLock  readLock()方法。当写入数据时锁定对象的写与读操作,只允许一个线程写入。当读数据时,不允许写入数据,可以允许多个线程读。

看代码吧:

package com.yao.thread;

import java.util.Arrays;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ArrayListReentrantReadWriteLock {
	private ReadWriteLock rwLock = new ReentrantReadWriteLock();
	private int next;
	private Object[] list;
	
	public ArrayListReentrantReadWriteLock(int capacity){
		list = new Object[capacity];
	}
	
	public ArrayListReentrantReadWriteLock(){
		this(16);
	}
	
	public void add(Object obj) {
		try {
			rwLock.writeLock().lock();
			if (next == list.length) {
				list = Arrays.copyOf(list, list.length * 2);
			}
			list[next++] = obj;
		} finally {
			rwLock.writeLock().unlock();
		}
	}
	
	public Object get(int index) {
		try {
			rwLock.readLock().lock();
			return list[index];
		} finally {
			rwLock.readLock().unlock();
		}
	}
	
	public int size(){
		try {
			rwLock.readLock().lock();
			return next;
		} finally {
			rwLock.readLock().unlock();
		}
	}
}



你可能感兴趣的:(多线程)