多线程并发线程的读写锁


/*
读写锁,读读不互斥,读写互斥,写写互斥
 互斥的放在同一个类中 */

import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
 publicclass ReadWriteLockTest { 
   publicstaticvoid main(String[] args) {
      final Queue3 q3 = new Queue3();
      for(inti=0;i<3;i++)
      { 
        new Thread(){
           publicvoid run(){
              while(true){
                 q3.get();            
              }
           }
        }.start();
                      
        new Thread(){
           publicvoid run(){
              while(true){
                 q3.put(new Random().nextInt(10000));
              }
           }          
        }.start();
      }
   }
}
 
class Queue3{
   private Object data = null;//共享数据,只能有一个线程能写该数据,但可以有多个线程同时读该数据。
   ReadWriteLock rwl = new ReentrantReadWriteLock();
  
   publicvoid 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(InterruptedException e){
        e.printStackTrace();
      }finally{
        rwl.readLock().unlock();
      }
   }
  
   publicvoid 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 (InterruptedException e){
        e.printStackTrace();
      }finally{
        rwl.writeLock().unlock();
      }
   }
}



读写锁的cache
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
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 = "aaaa";//实际失去queryDB();
              }
           }finally{
              rwl.writeLock().unlock();
           }
           rwl.readLock().lock();
        }
      }finally{
        rwl.readLock().unlock();
      }
      return value;
   }
}


猜你喜欢

转载自houston123.iteye.com/blog/2316584