Lock和读写锁ReadWriteLock和缓存实例

来源:互联网 发布:网络本统考的时间 编辑:程序博客网 时间:2024/06/06 10:37

1:lock和synchronized对比

[java] view plain copy
  1. import java.util.concurrent.locks.Lock;  
  2. import java.util.concurrent.locks.ReentrantLock;  
  3.   
  4.   
  5. public class LockTest {  
  6.   
  7.     /** 
  8.      * @param args 
  9.      */  
  10.     public static void main(String[] args) {  
  11.         new LockTest().init();  
  12.     }  
  13.       
  14.     private void init(){  
  15.         final Outputer outputer = new Outputer();  
  16.         new Thread(new Runnable(){  
  17.             @Override  
  18.             public void run() {  
  19.                 while(true){  
  20.                     try {  
  21.                         Thread.sleep(10);  
  22.                     } catch (InterruptedException e) {  
  23.                         // TODO Auto-generated catch block  
  24.                         e.printStackTrace();  
  25.                     }  
  26.                     outputer.output("zhangxiaoxiang");  
  27.                 }  
  28.                   
  29.             }  
  30.         }).start();  
  31.           
  32.         new Thread(new Runnable(){  
  33.             @Override  
  34.             public void run() {  
  35.                 while(true){  
  36.                     try {  
  37.                         Thread.sleep(10);  
  38.                     } catch (InterruptedException e) {  
  39.                         // TODO Auto-generated catch block  
  40.                         e.printStackTrace();  
  41.                     }  
  42.                     outputer.output("lihuoming");  
  43.                 }  
  44.                   
  45.             }  
  46.         }).start();  
  47.           
  48.     }  
  49.   
  50.     static class Outputer{  
  51.         Lock lock = new ReentrantLock();  
  52.         public void output(String name){  
  53.             int len = name.length();  
  54.             lock.lock();  
  55.             try{  
  56.                 for(int i=0;i<len;i++){  
  57.                     System.out.print(name.charAt(i));  
  58.                 }  
  59.                 System.out.println();  
  60.             }finally{  
  61.                 lock.unlock();  
  62.             }  
  63.         }  
  64.           
  65.         public synchronized void output2(String name){  
  66.             int len = name.length();  
  67.             for(int i=0;i<len;i++){  
  68.                     System.out.print(name.charAt(i));  
  69.             }  
  70.             System.out.println();  
  71.         }  
  72.           
  73.         public static synchronized void output3(String name){  
  74.             int len = name.length();  
  75.             for(int i=0;i<len;i++){  
  76.                     System.out.print(name.charAt(i));  
  77.             }  
  78.             System.out.println();  
  79.         }     
  80.     }  
  81. }  


2.读写锁:ReadWriteLock

[java] view plain copy
  1. import java.util.Random;  
  2. import java.util.concurrent.locks.ReadWriteLock;  
  3. import java.util.concurrent.locks.ReentrantReadWriteLock;  
  4.   
  5. public class ReadWriteLockTest {  
  6.     public static void main(String[] args) {  
  7.         final Queue3 q3 = new Queue3();  
  8.         for(int i=0;i<3;i++)  
  9.         {  
  10.             new Thread(){  
  11.                 public void run(){  
  12.                     while(true){  
  13.                         q3.get();                         
  14.                     }  
  15.                 }  
  16.                   
  17.             }.start();  
  18.   
  19.             new Thread(){  
  20.                 public void run(){  
  21.                     while(true){  
  22.                         q3.put(new Random().nextInt(10000));  
  23.                     }  
  24.                 }             
  25.                   
  26.             }.start();  
  27.         }  
  28.           
  29.     }  
  30. }  
  31.   
  32. class Queue3{  
  33.     private Object data = null;//共享数据,只能有一个线程能写该数据,但可以有多个线程同时读该数据。  
  34.     ReadWriteLock rwl = new ReentrantReadWriteLock();  
  35.     public void get(){  
  36.         rwl.readLock().lock();  
  37.         try {  
  38.             System.out.println(Thread.currentThread().getName() + " be ready to read data!");  
  39.             Thread.sleep((long)(Math.random()*1000));  
  40.             System.out.println(Thread.currentThread().getName() + "have read data :" + data);             
  41.         } catch (InterruptedException e) {  
  42.             e.printStackTrace();  
  43.         }finally{  
  44.             rwl.readLock().unlock();  
  45.         }  
  46.     }  
  47.       
  48.     public void put(Object data){  
  49.   
  50.         rwl.writeLock().lock();  
  51.         try {  
  52.             System.out.println(Thread.currentThread().getName() + " be ready to write data!");                    
  53.             Thread.sleep((long)(Math.random()*1000));  
  54.             this.data = data;         
  55.             System.out.println(Thread.currentThread().getName() + " have write data: " + data);                   
  56.         } catch (InterruptedException e) {  
  57.             e.printStackTrace();  
  58.         }finally{  
  59.             rwl.writeLock().unlock();  
  60.         }  
  61.           
  62.       
  63.     }  
  64. }  

3.用写锁实现库存递减

import java.util.concurrent.locks.ReadWriteLock;import java.util.concurrent.locks.ReentrantReadWriteLock;public class ReadWriteLockTest {public static boolean flag = true;public static void main(String[] args) {final Queue3 q3 = new Queue3();for (int i = 0; i < 3; i++) {new Thread() {public void run() {while (ReadWriteLockTest.flag) {q3.put();}}}.start();}}}class Queue3 {private Integer data = 10;// 共享数据,只能有一个线程能写该数据,但可以有多个线程同时读该数据。final ReadWriteLock lock = new ReentrantReadWriteLock();public void put() {lock.writeLock().lock();// 写锁开启,这时只有一个写线程进入try {System.out.println(Thread.currentThread().getName() + " have write data: " + data);if (data == 0) {ReadWriteLockTest.flag = false;return;}data--;} finally {lock.writeLock().unlock();}}}



4.用读写锁实现一个简单缓存机制

[java] view plain copy
  1. import java.util.HashMap;  
  2. import java.util.Map;  
  3. import java.util.concurrent.locks.ReadWriteLock;  
  4. import java.util.concurrent.locks.ReentrantReadWriteLock;  
  5.   
  6. public class CacheDemo {  
  7.   
  8.     private Map<String, Object> cache = new HashMap<String, Object>();  
  9.     public static void main(String[] args) {  
  10.         // TODO Auto-generated method stub  
  11.   
  12.     }  
  13.   
  14.     private ReadWriteLock rwl = new ReentrantReadWriteLock();  
  15.     public  Object getData(String key){  
  16.         rwl.readLock().lock();  
  17.         Object value = null;  
  18.         try{  
  19.             value = cache.get(key);  
  20.             if(value == null){  
  21.                 rwl.readLock().unlock();  
  22.                 rwl.writeLock().lock();  
  23.                 try{  
  24.                     if(value==null){  
  25.                         value = "aaaa";//实际失去queryDB();  
  26.                     }  
  27.                 }finally{  
  28.                     rwl.writeLock().unlock();  
  29.                 }  
  30.                 rwl.readLock().lock();  
  31.             }  
  32.         }finally{  
  33.             rwl.readLock().unlock();  
  34.         }  
  35.         return value;  
  36.     }  
  37. }  


 

0 0
原创粉丝点击