// 添加非公平获取尝试同步状态的方法,该方法体现非公平性与重入特性 finalbooleannonfairTryAcquire(int acquires){ // 获取当前线程 final Thread current = Thread.currentThread(); // 获取当前同步状态 int c = getState(); // 如果没有线程获取同步状态 if (c == 0) { // 使用CAS方法获取同步状态,这里体现非公平性,因为没有判断等待队列里是否有其他线程在等待获取同步状态 if (compareAndSetState(0, acquires)) { // 获取成功则设置独占线程 setExclusiveOwnerThread(current); returntrue; } } // 否则当前线程已经获取过同步状态 elseif (current == getExclusiveOwnerThread()) { // 直接在原基础状态值加上acquires,体现重入性 int nextc = c + acquires; // 如果nextc小于0表示线程获取锁的次数已经超过最大值 if (nextc < 0) // overflow thrownew Error("Maximum lock count exceeded"); // 设置新的同步状态 setState(nextc); returntrue; } returnfalse; }
// 重写tryRelease方法,对应公平与非公平锁都适用,体现重入性 protectedfinalbooleantryRelease(int releases){ int c = getState() - releases; if (Thread.currentThread() != getExclusiveOwnerThread()) thrownew IllegalMonitorStateException(); boolean free = false; if (c == 0) { free = true; setExclusiveOwnerThread(null); } setState(c); return free; }
// 判断当前线程是否独占锁 protectedfinalbooleanisHeldExclusively(){ // While we must in general read state before owner, // we don't need to do so to check if current thread is owner return getExclusiveOwnerThread() == Thread.currentThread(); }
// 创建等待条件 final ConditionObject newCondition(){ returnnew ConditionObject(); }