package Test;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/*
* 互斥锁稍微弱化的版本:读写锁,可以一起读,读写互斥写写互斥
* */
public class RWLock {
static int k = 1;
static ReadWriteLock rwl = new ReentrantReadWriteLock();
public static void main(String[] args){
for(int i=0;i<2;i++){
new Thread(new Runnable(){
public void run(){
while(true){
rwl.readLock().lock();
try{
System.out.println("读:"+Thread.currentThread().getName()+":"+k);
try{Thread.sleep(500);}catch(InterruptedException e){}
}finally{rwl.readLock().unlock();}
}
}
}).start();
}
for(int i=0;i<2;i++){
new Thread(new Runnable(){
public void run(){
while(true){
rwl.writeLock().lock();
try{
k = new Random().nextInt(10);
try {
Thread.sleep(500);
System.out.println("写:"+Thread.currentThread().getName()+":"+k);
} catch (InterruptedException e) {}
}finally{rwl.writeLock().unlock();}
}
}
}).start();
}
}
}
读写锁的一个应用:
package Test;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/*
* 读写锁的例子:cache
* */
public class SynCache {
private Map<String,Object> map = new HashMap<String,Object>();
private ReadWriteLock rwl = new ReentrantReadWriteLock();
public Object get(String s){
Object o = null;
rwl.readLock().lock();
try{
o = map.get(s);
if(o==null){
rwl.readLock().unlock();
rwl.writeLock().lock();
try{
if(map.get(s)==null)
o = "get data from base";
else //之前已经有个线程去DB得到数据
o = map.get(s);
}finally{
rwl.writeLock().unlock();
}
}
}finally{rwl.readLock().unlock();}
return o;
}
}