当前位置:   article > 正文

JUC之ReadWriteLock的简介与使用_juc readock

juc readock

1.ReadWriteLock简介


2. ReadWriteLock应用

  1. package rw;
  2. import java.util.HashMap;
  3. import java.util.Map;
  4. import java.util.concurrent.locks.ReadWriteLock;
  5. import java.util.concurrent.locks.ReentrantReadWriteLock;
  6. /**
  7. *
  8. * 独占锁(写锁):一次只能被一个线程占用
  9. * 共享锁(读锁):多个线程可以同时占有
  10. *
  11. * ReadWriteLock
  12. * 读,读可以共存
  13. * 读,写不可共存
  14. * 写,写不可共存
  15. * @author Admin
  16. *
  17. */
  18. public class ReadWriteLockDemo {
  19. public static void main(String[] args) {
  20. // MyCache myCacheLock = new MyCache();
  21. MyCacheLock myCacheLock = new MyCacheLock();
  22. // 写入
  23. for (int i = 1; i <= 5; i++) {
  24. final int temp = i;
  25. new Thread(() -> {
  26. myCacheLock.put(temp + "", temp + "");
  27. },String.valueOf(i)).start();
  28. }
  29. // 读取
  30. for (int i = 1; i <= 5; i++) {
  31. final int temp = i;
  32. new Thread(() -> {
  33. myCacheLock.get(temp + "");
  34. },String.valueOf(i)).start();
  35. }
  36. }
  37. }
  38. class MyCacheLock {
  39. private volatile Map<String, Object> map = new HashMap<>();
  40. // 读写锁,更加细粒度的控制
  41. private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
  42. // 存,写,只能一个线程进入
  43. public void put(String key, Object value) {
  44. readWriteLock.writeLock().lock();
  45. try {
  46. System.out.println(Thread.currentThread().getName() + "写入" + key);
  47. map.put(key, value);
  48. System.out.println(Thread.currentThread().getName() + "写入ok");
  49. } finally {
  50. readWriteLock.writeLock().unlock();
  51. }
  52. }
  53. // 取,读,所有人都可以读
  54. public void get(String key) {
  55. readWriteLock.readLock().lock();
  56. try {
  57. System.out.println(Thread.currentThread().getName() + "读取" + key);
  58. Object object = map.get(key);
  59. System.out.println(Thread.currentThread().getName() + "读取ok");
  60. } finally {
  61. readWriteLock.readLock().unlock();
  62. }
  63. }
  64. }
  65. //自定义缓存
  66. class MyCache {
  67. private volatile Map<String, Object> map = new HashMap<>();
  68. // 存,写
  69. public void put(String key, Object value) {
  70. System.out.println(Thread.currentThread().getName() + "写入" + key);
  71. map.put(key, value);
  72. System.out.println(Thread.currentThread().getName() + "写入ok");
  73. }
  74. // 取,读
  75. public void get(String key) {
  76. System.out.println(Thread.currentThread().getName() + "读取" + key);
  77. Object object = map.get(key);
  78. System.out.println(Thread.currentThread().getName() + "读取ok");
  79. }
  80. }

控制台

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/956181
推荐阅读
相关标签
  

闽ICP备14008679号