首页>代码>java多线程类ReentrantReadWriteLock读写锁实例代码及内存缓存工具类>/demo/src/com/zuidaima/thread/ReadWriteLockDemo.java
package com.zuidaima.thread;
import java.util.Random;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
*
* ReentrantReadWriteLock读写锁的demo
* @author luoy
*
*/
public class ReadWriteLockDemo {
public static void main(String[] args) {
final Demo1 demo = new Demo1();
//测试读取数据方法
for(int i=0;i<3;i++){
new Thread(){
public void run(){
while(true){
demo.get();
}
}
}.start();
}
//测试写数据方法
for(int i=0;i<3;i++){
new Thread(){
public void run(){
while(true){
demo.put(new Random().nextInt(10000));
}
}
}.start();
}
}
}
class Demo1{
private Object data = null;//模拟数据
private ReentrantReadWriteLock RWL = new ReentrantReadWriteLock();// 创建一个读写锁对象
//读取数据方法
public void get(){
RWL.readLock().lock();//上读锁
System.out.println(Thread.currentThread().getName()+" 这个时候只能读数据咯....");
try {
Thread.sleep((long)new Random().nextInt(10000));
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(Thread.currentThread().getName()+" 发现可读数据--->:"+data);
RWL.readLock().unlock();//释放读锁
}
//写数据方法
public void put(Object data){
RWL.writeLock().lock();//上写锁
System.out.println(Thread.currentThread().getName()+" 这个时候不能写数据了...");
try {
Thread.sleep((long)new Random().nextInt(10000));
} catch (Exception e) {
// TODO: handle exception
}
this.data = data;
System.out.println(Thread.currentThread().getName()+" 发现可读数据--->:"+data);
RWL.writeLock().unlock();//释放写锁
}
}
最近下载更多
aisuzhen LV10
2019年9月17日
springbootzxx LV5
2019年7月26日
倪卟懂 LV18
2019年5月7日
afeng992211 LV14
2018年10月12日
tyd888 LV11
2018年9月27日
superman_0001 LV5
2018年7月18日
CLATZJ LV19
2018年3月25日
der2030 LV17
2018年1月23日
15735184511 LV7
2018年1月4日
dulante LV4
2017年10月25日

最近浏览