提高性能
读写锁:分为读锁和写锁,多个读锁不互斥,读锁与写锁互斥,写锁与写锁互斥,这是由JVM控制的,我们只需要上好相应的锁即可。如果代码只读数据,可以很多人同时读,但不能同时写,那就上读锁;如果代码修改数据,只能有一个人在写,且不能同时读取,那就上写锁。总之,读的时候上读锁,写的时候上写锁。
import java.util.Random;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;public class ReadWriteLockTest {public static void main(String[] args) {final Queue3 q3 &#61; new Queue3();for(int i&#61;0;i<3;i&#43;&#43;){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 &#61; null;//共享数据&#xff0c;只能有一个线程能写该数据&#xff0c;但可以有多个线程同时读该数据。ReadWriteLock rwl &#61; new ReentrantReadWriteLock();public void get(){rwl.readLock().lock();try {System.out.println(Thread.currentThread().getName() &#43; " be ready to read data!");Thread.sleep((long)(Math.random()*1000));System.out.println(Thread.currentThread().getName() &#43; "have read data :" &#43; data); } catch (InterruptedException e) {e.printStackTrace();}finally{rwl.readLock().unlock();}}public void put(Object data){rwl.writeLock().lock();try {System.out.println(Thread.currentThread().getName() &#43; " be ready to write data!"); Thread.sleep((long)(Math.random()*1000));this.data &#61; data; System.out.println(Thread.currentThread().getName() &#43; " have write data: " &#43; data); } 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;public class CacheDemo {private Map cache &#61; new HashMap();public static void main(String[] args) {// TODO Auto-generated method stub}private ReadWriteLock rwl &#61; new ReentrantReadWriteLock();public Object getData(String key){rwl.readLock().lock();Object value &#61; null;try{value &#61; cache.get(key);if(value &#61;&#61; null){rwl.readLock().unlock();rwl.writeLock().lock();try{if(value&#61;&#61;null){value &#61; "aaaa";//实际是去queryDB();}}finally{rwl.writeLock().unlock();}rwl.readLock().lock();}}finally{rwl.readLock().unlock();}return value;}
}
本文出自 “点滴积累” 博客&#xff0c;请务必保留此出处http://tianxingzhe.blog.51cto.com/3390077/1716731