您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇文章主要讲解了“JAVA多线程用JDK1.5提供的读写锁实现高并发本地缓存工具类”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“JAVA多线程用JDK1.5提供的读写锁实现高并发本地缓存工具类”吧!
package com.study; import java.util.LinkedHashMap; import java.util.Map; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class ReadWriteLockDemo { private static Map<String, Object> cacheMap = new LinkedHashMap<String, Object>(); public static void main(String[] args) { ReadWriteLockDemo readWriteLockDemo = new ReadWriteLockDemo(); final CacheUtils cacheUtils = readWriteLockDemo.new CacheUtils(); Thread thread = new Thread(new Runnable() { @Override public void run() { for(Integer index = 0;index <= 100;index ++){ System.out.println(cacheUtils.putCache(index.toString())); } } }); thread.start(); Thread thread2 = new Thread(new Runnable() { @Override public void run() { for(Integer index = 0;index <= 100;index ++){ System.out.println(cacheUtils.putCache(index.toString())); } } }); thread2.start(); } class CacheUtils { // 定义一把读写锁 ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); public Object putCache(String key){ //进来时,先用读锁进行上锁 readWriteLock.readLock().lock(); Object value = null; try { value = cacheMap.get(key); if(value == null){ readWriteLock.readLock().unlock(); try { readWriteLock.writeLock().lock(); if(value == null){ //此处实际上是查询DB value = "huangkejie" + key; cacheMap.put(key, value); } } catch (Exception e) { e.printStackTrace(); }finally{ readWriteLock.writeLock().unlock(); } readWriteLock.readLock().lock(); } } catch (Exception error) { error.printStackTrace(); } finally{ readWriteLock.readLock().unlock(); } return value; } } }
感谢各位的阅读,以上就是“JAVA多线程用JDK1.5提供的读写锁实现高并发本地缓存工具类”的内容了,经过本文的学习后,相信大家对JAVA多线程用JDK1.5提供的读写锁实现高并发本地缓存工具类这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。