java.util.concurrent.locks.ReentrantReadWriteLock
使用Java提供的读写锁实现读和写操作;
package com.dong.testThread;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
*
* 读写锁:读写锁分离,有效的帮助减少锁竞争,
* 读写锁允许多个线程同时读,即线程之间并行操作
* 但是涉及到写操作时,则会进行同步执行,只要线程在执行写操作,则会阻塞请求线程,直到写操作完成,
*
* 即读-读,之间不阻塞
* 即读-写,读阻塞写,写也会阻塞读
* 即写-写,写写互阻塞;
*
* @author liuD
*
*/
public class TestReadWriteLock {
/* 程序是先开启读线程,然后再开启写线程
* 结果分析:
* 如果读线程过少的话,读线程会很快执行完,我们看不到写线程的结果,所以读写线程尽量差不过
* 选取某次程序运行结果:
* Thread-0 读取数据 值0
Thread-10 读取数据 值0
Thread-9 读取数据 值0
Thread-7 读取数据 值0
Thread-4 读取数据 值0
Thread-3 读取数据 值0
Thread-6 读取数据 值0
Thread-8 读取数据 值0
Thread-5 读取数据 值0
Thread-2 读取数据 值0
Thread-17 读取数据 值0
Thread-1 读取数据 值0
Thread-36 写入数据,-1253473407
Thread-26 写入数据,1490518821
Thread-27 写入数据,676487849
Thread-31 写入数据,-154073432
Thread-24 写入数据,-526063573
Thread-28 写入数据,-1425534995
Thread-29 写入数据,-732534000
Thread-33 写入数据,1438688294
Thread-23 写入数据,-2094184880
Thread-34 写入数据,1927228702
Thread-25 写入数据,-1920288960
Thread-32 写入数据,-1140774534
Thread-22 写入数据,1375894526
Thread-18 写入数据,-180427778
Thread-20 写入数据,56249129
Thread-21 写入数据,1501904576
Thread-15 读取数据 值1501904576
Thread-14 读取数据 值1501904576
Thread-16 读取数据 值1501904576
Thread-12 读取数据 值1501904576
Thread-13 读取数据 值1501904576
Thread-11 读取数据 值1501904576
Thread-19 写入数据,-109807713
Thread-35 写入数据,-715405539
Thread-37 写入数据,1966529814
Thread-30 写入数据,103373668
可以看出读线程,刚开始再读数值,从相同的值,可以看出读线程之间不会阻塞,
如果有线程想写,则会进行阻塞,然后写的过程中,读也会阻塞,
写写操作时同步的,
*
*/
private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private static Lock readLock = readWriteLock.readLock();
private static Lock writeLock = readWriteLock.writeLock();
private int value;
public static void main(String[] args) {
final TestReadWriteLock test = new TestReadWriteLock();
Runnable readRunnale = new Runnable() {
public void run() {
try {
test.handleRead(readLock);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
};
Runnable writeRunnable = new Runnable() {
public void run() {
try {
test.handleWrite(writeLock, new Random().nextInt());
} catch (Exception e) {
e.printStackTrace();
}
}
};
for(int i = 0;i<18;i++) {
new Thread(readRunnale).start();
}
for(int j = 0 ;j<20;j++) {
new Thread(writeRunnable).start();
}
}
public Object handleRead(Lock lock ) throws InterruptedException {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() + " 读取数据 值" + value);
return value;
} finally {
lock.unlock();
}
}
public void handleWrite(Lock lock,int index) throws InterruptedException {
try {
lock.lock();
//模拟写操作,让写线程进入写操作,来观察读操作的情况;
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+ " 写入数据,"+ index);
value = index;
} finally {
lock.unlock();
}
}
}
代码参考:《Java高并发程序设计》 -葛一鸣 郭超,由衷感谢此书作者为我们提供学习内容