1. 优秀内容:https://mp.weixin.qq.com/s/224pnAA6e8LvFcbJNHpWug

一.非公平锁

非公平锁会导致锁饥饿现象

  1. final boolean nonfairTryAcquire(int acquires) {
  2. final Thread current = Thread.currentThread();
  3. int c = getState();
  4. if (c == 0) {
  5. if (compareAndSetState(0, acquires)) {
  6. setExclusiveOwnerThread(current);
  7. return true;
  8. }
  9. }
  10. else if (current == getExclusiveOwnerThread()) {
  11. int nextc = c + acquires;
  12. if (nextc < 0) // overflow
  13. throw new Error("Maximum lock count exceeded");
  14. setState(nextc);
  15. return true;
  16. }
  17. return false;
  18. }

ReenTrantLock - 图1

二.公平锁

公平锁与非公平锁的区别是公平锁需要去判断是否有前驱节点如果有需要去阻塞队列等待

  1. protected final boolean tryAcquire(int acquires) {
  2. final Thread current = Thread.currentThread();
  3. int c = getState();
  4. if (c == 0) {
  5. if (!hasQueuedPredecessors() &&
  6. compareAndSetState(0, acquires)) {
  7. setExclusiveOwnerThread(current);
  8. return true;
  9. }
  10. }
  11. else if (current == getExclusiveOwnerThread()) {
  12. int nextc = c + acquires;
  13. if (nextc < 0)
  14. throw new Error("Maximum lock count exceeded");
  15. setState(nextc);
  16. return true;
  17. }
  18. return false;
  19. }

ReenTrantLock - 图2

三.可重入锁

四.死锁检查

1.1 jstack

  1. 1.1.1 使用jps -l 命令查出当前正在运行的线程

ReenTrantLock - 图3

  1. 1.1.2 使用 jstack+线程id 查看线程执行情况 出现deadlock说明有死锁

ReenTrantLock - 图4

1.2jconsole

  1. 在控制台输入jconsole命令,连接线程id

ReenTrantLock - 图5
ReenTrantLock - 图6