1 import java.util.Random; 2 import java.util.concurrent.locks.ReadWriteLock; 3 import java.util.concurrent.locks.ReentrantReadWriteLock; 4 /** 5 * 6 * @author LiTaiQing 7 * 8 */ 9 public class ReadWriteLockTest { 10 public static void main(String[] args){ 11 final Queue3 q3 = new Queue3(); 12 13 for (int i = 0; i < 3; i++) { 14 new Thread(){ 15 @Override 16 public void run(){ 17 while(true){ 18 q3.get(); 19 } 20 } 21 }.start(); 22 23 new Thread(){ 24 @Override 25 public void run() { 26 q3.put(new Random().nextInt(10000)); 27 }; 28 }.start(); 29 30 } 31 32 } 33 34 } 35 class Queue3{ 36 private Object data = null;//共享数据,只能有一个线程能写该数据,但可以有多个线程同时读该数据。 37 //读写锁-实现类ReentrantReadWriteLock 38 ReadWriteLock rwl = new ReentrantReadWriteLock(); 39 public void get(){ 40 rwl.readLock().lock(); 41 try { 42 System.out.println(Thread.currentThread().getName() + " be ready to read data!"); 43 Thread.sleep((long)(Math.random()*1000)); 44 System.out.println(Thread.currentThread().getName() + "have read data :" + data); 45 } catch (InterruptedException e) { 46 e.printStackTrace(); 47 }finally{ 48 rwl.readLock().unlock(); 49 } 50 } 51 public void put(Object data){ 52 rwl.writeLock().lock(); 53 try { 54 System.out.println(Thread.currentThread().getName() + " be ready to write data!"); 55 Thread.sleep((long)(Math.random()*1000)); 56 this.data = data; 57 System.out.println(Thread.currentThread().getName() + " have write data: " + data); 58 } catch (InterruptedException e) { 59 e.printStackTrace(); 60 }finally{ 61 rwl.writeLock().unlock(); 62 } 63 } 64 }
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 * 面试题,写一个缓存系统 7 * @author LiTaiQing 8 * 9 */ 10 public class CacheDemo { 11 12 private Map<String,Object> cache = new HashMap<String,Object>(); 13 14 public static void main(String[] args) { 15 16 } 17 /** 18 * 读写锁的应用 19 */ 20 private ReadWriteLock rwl = new ReentrantReadWriteLock(); 21 public Object getData(String key){ 22 rwl.readLock().lock(); 23 Object value = null; 24 try{ 25 value = cache.get(key); 26 if(value == null){ 27 rwl.readLock().unlock(); 28 rwl.writeLock().lock(); 29 try{ 30 if(value == null){ 31 value = "abc";//实际是去queryDB(); 32 } 33 }finally{ 34 rwl.writeLock().unlock(); 35 } 36 rwl.readLock().lock(); 37 } 38 }finally{ 39 rwl.readLock().unlock(); 40 } 41 return value; 42 } 43 44 }
时间: 2024-11-10 13:38:17