自定义显式锁BooleanLock

一时失言乱红尘 2023-01-07 12:26 219阅读 0赞

今天看到Java高并发编程详解一书中的自定义显式锁代码不错,写下来以便日后查阅

  1. public interface Lock {
  2. void lock() throws InterruptedException;
  3. void lock(long mills) throws InterruptedException, TimeoutException;
  4. void unlock();
  5. List<Thread> getBooleanThreads();
  6. }
  7. package com.thread.test.booleanlock;
  8. import java.util.ArrayList;
  9. import java.util.Collections;
  10. import java.util.List;
  11. import java.util.Optional;
  12. import java.util.concurrent.TimeoutException;
  13. import static java.lang.Thread.currentThread;
  14. public class BooleanLock implements Lock {
  15. //当前线程
  16. private Thread currentThread;
  17. //锁是否被占用
  18. private boolean locked = false;
  19. //阻塞线程集合
  20. private final List<Thread> blockedList = new ArrayList<>();
  21. @Override
  22. public void lock() throws InterruptedException {
  23. synchronized (this) {
  24. while (locked) {
  25. //暂存当前线程
  26. final Thread tempThread = currentThread();
  27. try {
  28. if (!blockedList.contains(currentThread())) {
  29. blockedList.add(currentThread());
  30. }
  31. this.wait();
  32. } catch (InterruptedException e) {
  33. //如果当前线程被中断,则将当前线程从list中移除,避免内存泄露
  34. blockedList.remove(tempThread);
  35. //继续抛出中断异常
  36. throw e;
  37. }
  38. }
  39. blockedList.remove(currentThread());
  40. this.locked = true;
  41. this.currentThread = currentThread();
  42. }
  43. }
  44. @Override
  45. public void lock(long mills) throws InterruptedException, TimeoutException {
  46. synchronized (this) {
  47. if (mills < 0) {
  48. //可抛异常亦可执行lock()方法,这里执行lock()方法
  49. this.lock();
  50. } else {
  51. long remainingMills = mills;
  52. long endMills = System.currentTimeMillis() + remainingMills;
  53. while (locked) {
  54. if (remainingMills <= 0) {
  55. throw new TimeoutException("cant get the lock during " + mills + " ms.");
  56. }
  57. if (!blockedList.contains(currentThread())) {
  58. blockedList.add(currentThread());
  59. }
  60. this.wait(mills);
  61. remainingMills = endMills - System.currentTimeMillis();
  62. }
  63. blockedList.remove(currentThread());
  64. this.locked = true;
  65. this.currentThread = currentThread();
  66. }
  67. }
  68. }
  69. @Override
  70. public void unlock() {
  71. synchronized (this) {
  72. if (currentThread == currentThread()) {
  73. this.locked = false;
  74. Optional.of(currentThread().getName() + " release the lock.").ifPresent(System.out::print);
  75. this.notifyAll();
  76. }
  77. }
  78. }
  79. @Override
  80. public List<Thread> getBooleanThreads() {
  81. return Collections.unmodifiableList(blockedList);
  82. }
  83. }

发表评论

表情:
评论列表 (有 0 条评论,219人围观)

还没有评论,来说两句吧...

相关阅读

    相关 示例

    tryLock在一定时间内获取不到锁不会一直阻塞,会返回false,然后线程会继续向下走。 package com.iteye.yuanyuan7891.thread

    相关

    显式锁:高级功能,轮询,定时,中断,公平性: 非公平发出请求时锁可用可以直接抢,否则也要排队,公平的只要锁不可用或前面有人就去排队 公平性很好,但没必要,而且会带来性能问题