Java读写锁基本使用

ReadWriteLock使得你可以同时具有多个读取者,只要他们都不试图写入即可。如果写锁被其他任务持有,那么任何读取者均不能访问,直至这个写锁被释放为止。
ReadWriteLock能否提高性能是不确定的,取决于数据读取与修改频率相比较的结果,读取和写入操作的时间,竞争的线程数以及是否是多处理器等等。
下面展示了ReadWriteLock最基本的用法。

package concurrency;

//: concurrency/ReaderWriterList.java
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.util.*;

public class ReaderWriterList<T> {
private ArrayList<T> lockedList;
// Make the ordering fair:
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);

public ReaderWriterList(int size, T initialValue) {
lockedList = new ArrayList<T>(Collections.nCopies(size, initialValue));
}

public T set(int index, T element) {
Lock wlock = lock.writeLock();
wlock.lock();
try {
return lockedList.set(index, element);
} finally {
wlock.unlock();
}
}

public T get(int index) {
Lock rlock = lock.readLock();
rlock.lock();
try {
// Show that multiple readers
// may acquire the read lock:
if (lock.getReadLockCount() > 1)
System.out.println(lock.getReadLockCount());
return lockedList.get(index);
} finally {
rlock.unlock();
}
}

public static void main(String[] args) throws Exception {
new ReaderWriterListTest(30, 1);
}
}

class ReaderWriterListTest {
ExecutorService exec = Executors.newCachedThreadPool();
private final static int SIZE = 100;
private static Random rand = new Random(47);
private ReaderWriterList<Integer> list = new ReaderWriterList<Integer>(
SIZE, 0);

private class Writer implements Runnable {
public void run() {
try {
for (int i = 0; i < 20; i++) { // 2 second test
list.set(i, rand.nextInt());
TimeUnit.MILLISECONDS.sleep(100);
}
} catch (InterruptedException e) {
// Acceptable way to exit
}
System.out.println("Writer finished, shutting down");
exec.shutdownNow();
}
}

private class Reader implements Runnable {
public void run() {
try {
while (!Thread.interrupted()) {
for (int i = 0; i < SIZE; i++) {
list.get(i);
TimeUnit.MILLISECONDS.sleep(1);
}
}
} catch (InterruptedException e) {
// Acceptable way to exit
}
}
}

public ReaderWriterListTest(int readers, int writers) {
for (int i = 0; i < readers; i++)
exec.execute(new Reader());
for (int i = 0; i < writers; i++)
exec.execute(new Writer());
}
} /* (Execute to see output) */// :~


程序输出结果如下:
24
25
22
19
17
16
...
...//省略
7
6
5
4
3
Writer finished, shutting down
set()方法获取写锁,get方法获取读锁,并且检查是否有多个线程获取了读锁,如果是就打印这种读取者的数量到控制台,以证明可以有多个读取者获得读锁。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值