关闭

java 之 读写锁 线程间互斥

1398人阅读 评论(0) 收藏 举报
import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 线程间互斥
 * @author ETHAN
 *
 */
public class ReadWriteLockTest {

	public static void main(String[] args) {
		final Queue3 q3 = new Queue3();
		for(int i=0;i<3;i++) {
			//三个读的线程
			new Thread() {
				public void run() {
					while(true) {
						q3.get();
					}
				}
			}.start();
			
			//三个写的线程
			new Thread() {
				public void run() {
					while(true) {
						q3.put(new Random().nextInt(100000));
					}
				}
			}.start();
		}
	}

}

/**
 * 读和写要互斥,放在一个类里
 * 读锁 不互斥,读和写锁互斥,写写锁互斥
 * @author ETHAN
 *
 */
class Queue3 {
	private Object data = null;//共享数据
	//不能用Lock,得用他的子类
	private ReadWriteLock rwl = new ReentrantReadWriteLock();
	
	public void get() {
		rwl.readLock().lock();
		try {
			System.out.println(Thread.currentThread().getName()+ " be ready to read data!");
			Thread.sleep((long)(Math.random()*1000));
			System.out.println(Thread.currentThread().getName()+" have read data: "+data);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			rwl.readLock().unlock();
		}
	}
	
	public void put(Object data) {
		rwl.writeLock().lock();
		
		try {
			System.out.println(Thread.currentThread().getName()+ " be ready to write data!");
			Thread.sleep((long)(Math.random()*1000));
			this.data = data;
			System.out.println(Thread.currentThread().getName()+" have write data: "+data);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			rwl.writeLock().unlock();
		}
	}
}


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 缓存系统
 * @author ETHAN
 *
 */
public class CacheDemo {

	private Map<String,Object> cache = new HashMap<String, Object>();
	
	public static void main(String[] args) {
		
	}
	
	private ReadWriteLock rwl = new ReentrantReadWriteLock();
	
	public Object getData(String key) {
		rwl.readLock().lock();
		Object value = null;
		try {
			value = cache.get(key);
			if(value==null) {
				rwl.readLock().unlock();
				//挂上写锁,查数据
				rwl.writeLock().lock();
				try {
					//再检查一次,防止其他线程,因为都可读,不互斥
					if(value==null) {
						value = "xxx";//query db
					}
				} finally {
					rwl.readLock().lock();//downgrade by acquiring the readlock
					rwl.writeLock().unlock();//有一种更新锁
				}
				
			} 
		} finally {
			rwl.readLock().unlock();
		}
		
		return value;
	}
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:614985次
    • 积分:7131
    • 等级:
    • 排名:第3143名
    • 原创:183篇
    • 转载:80篇
    • 译文:0篇
    • 评论:123条
    文章分类
    最新评论