优秀内容:https://mp.weixin.qq.com/s/224pnAA6e8LvFcbJNHpWug
一.非公平锁
非公平锁会导致锁饥饿现象
final boolean nonfairTryAcquire(int acquires) {final Thread current = Thread.currentThread();int c = getState();if (c == 0) {if (compareAndSetState(0, acquires)) {setExclusiveOwnerThread(current);return true;}}else if (current == getExclusiveOwnerThread()) {int nextc = c + acquires;if (nextc < 0) // overflowthrow new Error("Maximum lock count exceeded");setState(nextc);return true;}return false;}

二.公平锁
公平锁与非公平锁的区别是公平锁需要去判断是否有前驱节点如果有需要去阻塞队列等待
protected final boolean tryAcquire(int acquires) {final Thread current = Thread.currentThread();int c = getState();if (c == 0) {if (!hasQueuedPredecessors() &&compareAndSetState(0, acquires)) {setExclusiveOwnerThread(current);return true;}}else if (current == getExclusiveOwnerThread()) {int nextc = c + acquires;if (nextc < 0)throw new Error("Maximum lock count exceeded");setState(nextc);return true;}return false;}

三.可重入锁
四.死锁检查
1.1 jstack
1.1.1 使用jps -l 命令查出当前正在运行的线程

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

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


