package com.atguigu.juc; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; class MyCache1 { private volatile Map1.2、正确代码map = new HashMap<>(); public void put(String key, Object value) { System.out.println(Thread.currentThread().getName() + "t正在写" + key); //线程休眠,单位:秒 try { TimeUnit.MILLISECONDS.sleep(300); } catch (Exception e) { e.printStackTrace(); } map.put(key, value); System.out.println(Thread.currentThread().getName() + "t写完了" + key); } public Object get(String key) { Object result = null; System.out.println(Thread.currentThread().getName() + "t正在读" + key); //线程休眠,单位:毫秒 try { TimeUnit.MILLISECONDS.sleep(300); } catch (Exception e) { e.printStackTrace(); } result = map.get(key); System.out.println(Thread.currentThread().getName() + "t读完了" + result); return result; } } public class ReadWriteLockDemo1 { public static void main(String[] args) { MyCache1 myCache1 = new MyCache1(); for (int i = 1; i <= 5; i++) { final int num = i; new Thread(() -> { myCache1.put(num + "", +num + ""); }, String.valueOf(i)).start(); } for (int i = 1; i <= 5; i++) { final int num = i; new Thread(() -> { myCache1.get(num + ""); }, String.valueOf(i)).start(); } } }
package com.atguigu.juc; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; class MyCache2{ private volatile Mapmap = new HashMap<>(); private ReadWriteLock rwLock = new ReentrantReadWriteLock(); public void put(String key,Object value){ rwLock.writeLock().lock(); try{ System.out.println(Thread.currentThread().getName()+"t正在写"+key); //线程休眠,单位:毫秒 try { TimeUnit.MILLISECONDS.sleep(300); } catch (Exception e) { e.printStackTrace(); } map.put(key,value); System.out.println(Thread.currentThread().getName()+"t写完了"+key); System.out.println(); }catch (Exception e){ e.printStackTrace(); }finally { rwLock.writeLock().unlock(); } } public Object get(String key){ rwLock.readLock().lock(); Object result = null; try{ System.out.println(Thread.currentThread().getName()+"t正在读"+key); //线程休眠,单位:毫秒 try { TimeUnit.MILLISECONDS.sleep(300); } catch (Exception e) { e.printStackTrace(); } result = map.get(key); System.out.println(Thread.currentThread().getName()+"t读完了"+result); }catch (Exception e){ e.printStackTrace(); }finally { rwLock.readLock().unlock(); } return result; } } public class ReadWriteLockDemo2 { public static void main(String[] args) { MyCache2 myCache2 = new MyCache2(); for (int i = 1; i <= 5; i++) { final int num = i; new Thread(() -> { myCache2.put(num + "", +num + ""); }, String.valueOf(i)).start(); } for (int i = 1; i <= 5; i++) { final int num = i; new Thread(() -> { myCache2.get(num + ""); }, String.valueOf(i)).start(); } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)