這篇文章主要講解了“JAVA多線程用JDK1.5提供的讀寫鎖實現(xiàn)高并發(fā)本地緩存工具類”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“JAVA多線程用JDK1.5提供的讀寫鎖實現(xiàn)高并發(fā)本地緩存工具類”吧!
我們提供的服務(wù)有:網(wǎng)站設(shè)計、做網(wǎng)站、微信公眾號開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認證、天峨ssl等。為成百上千家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的天峨網(wǎng)站制作公司
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 MapcacheMap = new LinkedHashMap (); 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提供的讀寫鎖實現(xiàn)高并發(fā)本地緩存工具類”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對JAVA多線程用JDK1.5提供的讀寫鎖實現(xiàn)高并發(fā)本地緩存工具類這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!