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日
最近浏览更多
yyh1252  LV8 2023年7月25日
dixiu000  LV4 2023年4月14日
heqian  LV16 2022年10月17日
crosa_Don  LV18 2022年7月6日
MoonSight  LV1 2022年7月1日
liys1234  LV9 2022年4月27日
一道念  LV10 2022年1月29日
尹恒yingying  LV18 2021年4月14日
花椒谢霆锋  LV8 2021年3月2日
jay1992  LV14 2021年2月6日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友