Import Java.util.concurrent.TimeUnit;
Import Java.util.concurrent.locks.AbstractQueuedSynchronizer;
Import java.util.concurrent.locks.Condition;
Import Java.util.concurrent.locks.Lock; /** * When customizing internal Synchronizer, it is recommended to use static inner class */public class Customthreadlock implements lock{//static inner class, custom Synchronizer static class sync ex Tends abstractqueuedsynchronizer{//is in occupied public boolean isheldexclusively () {return g
Etstate () = = 1;
}//When the state is 0 o'clock gets the lock public boolean tryacquire (int arg) {//cas sets the state, which guarantees that the atomic status of the operation is currently 0, the operation success State is changed to 1 if (compareandsetstate (0, 1)) {//sets the current exclusive thread Setexclusiveownerthread (threa
D.currentthread ());
return true;
} return false;
}//When the state is 0 o'clock release lock public boolean tryrelease (int arg) {//If the Synchronizer Synchronizer state is not 0, the monitor illegal state exception is thrown if (getState ()! = 1) throw new IllegalmonitorstateexcePtion ();
The thread that sets the exclusive lock is null setexclusiveownerthread (NULL);
Set the sync status to 0 setState (0);
return true; }//returns Condition, each Condition contains a Condition queue Condition newcondition () {return new Conditiono
Bject ();
}}//action Agent to sync on private final sync sync = new sync ();
public void Lock () {//Exclusive Get synchronization state, get failure will go into synchronization queue wait, and invoke custom Tryacquire method Sync.acquire (1);
}//try to get the lock, if successful returns true, otherwise false public Boolean trylock () {//Call the method of the custom override return Sync.tryacquire (1); }/* * Try to time out acquire lock within timeout period, return true; return FALSE * Timeout acquisition lock fails to join synchronization queue wait, and node spin get lock Operation */Public Boolea N Trylock (long time, Timeunit unit) throws Interruptedexception {return Sync.tryacquirenanos (1, unit.
Tonanos (time));
}//Interruptible get lock public void lockinterruptibly () throws Interruptedexception {sync.acquireinterruptibly (1); }//Release lock public void Unlock () {sync.release (1);
} public Condition Newcondition () {return sync.newcondition ();
}//Determines whether the current thread is in the occupied state public Boolean islock () {return sync.isheldexclusively ();
}//Query If there are any threads waiting to get public boolean hasqueuedthreads () {return sync.hasqueuedthreads ();
}
}