多线程学习记录3-读写锁

来源:互联网 发布:c语言调试器 编辑:程序博客网 时间:2024/06/10 02:36

1:读写锁简单demo,读-写线程互斥,写-写线程互斥:

public class Test6 {public static void main(String[] args) {final Console cnl = new Console();for (int i=0; i<3; i++){new Thread(new Runnable() {@Overridepublic void run() {while (true){cnl.getData();}}}).start();new Thread(new Runnable() {@Overridepublic void run() {while (true){cnl.putData(10001);}}}).start();}}}class Console{private Object data = null;private ReadWriteLock rwl = new ReentrantReadWriteLock();public void getData(){rwl.readLock().lock();try {System.out.println(Thread.currentThread().getName() + ":开始读数据:");Thread.sleep((long)Math.random()*1000);System.out.println(Thread.currentThread().getName() + "读到数据:" + data);}catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{rwl.readLock().unlock();}}public void putData(Object data){rwl.writeLock().lock();try {System.out.println(Thread.currentThread().getName() + ":开始写入数据");Thread.sleep((long)Math.random()*1000);this.data = data;System.out.println(Thread.currentThread().getName() + ":写完数据:" + data);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{rwl.writeLock().unlock();}}}

2:简单的cache系统:


public class CacheDemo {private Map 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 = "ppp";}}finally{//填充完毕数据,恢复读锁。同一个线程加上了写锁,可以再加上读锁。一个线程中不会起冲突。rwl.readLock().lock();//解开写锁rwl.writeLock().unlock();}}}finally{rwl.readLock().unlock();}return value;}}



原创粉丝点击