java 多线程 day12 读写锁


import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Created by chengtao on 17/12/5.
* Lock 是替代 sycronized 的,而且sycronized无法实现读写锁
*/


public class Thread1201_ReadWriteLock {
public static void main(String[] args) {
final Queue3 q3 = new Queue3();
for(int i=0;i<30;i++)
{
new Thread(){
public void run(){
while(true){
q3.get();
}
}

}.start();

new Thread(){
public void run(){
while(true){
q3.put(new Random().nextInt(10000));
}
}

}.start();
}

}
}

class Queue3{
private Object data = null;//共享数据,只能有一个线程能写该数据,但可以有多个线程同时读该数据。
ReadWriteLock rwl = new ReentrantReadWriteLock();
public void get(){
rwl.readLock().lock();
try {
System.out.println(Thread.currentThread().getName() + " 准备去读 ----- 数据!");
Thread.sleep((long)(Math.random()*10));
System.out.println(Thread.currentThread().getName() + " 已经读到 ----- 数据 :" + data);
System.out.println();
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
rwl.readLock().unlock();
}
}

public void put(Object data){

rwl.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName() + " 准备去写数据 !");
Thread.sleep((long)(Math.random()*1000));
this.data = data;
System.out.println(Thread.currentThread().getName() + " 已经写入数据 : " + data);
System.out.println();
} catch (InterruptedException 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;

/**
* Created by chengtao on 17/12/5.
*/
public class Thread1202_ReadWriteLock_Cache {
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 = "aaaa";//实际失去queryDB();
}
}finally{
rwl.writeLock().unlock();
}
rwl.readLock().lock();
}
}finally{
rwl.readLock().unlock();
}
return value;
}
}
 
posted @ 2017-12-05 00:54  为爱奋斗不息  阅读(185)  评论(0编辑  收藏  举报