代码层面分析可重入原理

  1. final boolean nonfairTryAcquire(int acquires) {
  2. //获取当前的线程
  3. final Thread current = Thread.currentThread();
  4. //获取状态 0 代表当前线程可以获得这把锁
  5. int c = getState();
  6. if (c == 0) {
  7. if (compareAndSetState(0, acquires)) {//CAS
  8. //设置独占
  9. setExclusiveOwnerThread(current);
  10. return true;
  11. }
  12. }
  13. //如果当前状态不为0,则判断当前线程是否是正独占这把锁的线程
  14. else if (current == getExclusiveOwnerThread()) {
  15. int nextc = c + acquires;
  16. if (nextc < 0) // overflow
  17. //线程状态小于-1
  18. throw new Error("Maximum lock count exceeded");
  19. //设置状态
  20. setState(nextc);
  21. return true;
  22. }
  23. return false;
  24. }