您好,登錄后才能下訂單哦!
這篇文章主要講解了“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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。