Reentrantlock is a new class that JDK5 joins, and its usage is similar to synchronized. It requires the programmer to manually add lock and unlock code.
than the benefits of synchronized. It adds two methods:
L provides Trylock () when the method is called. If the lock is held by another object, it returns false.
L also one is the fair lock. At the time of constructing the Reentrantlock. It has a person of type Boolean parameter. This parameter is described using a fair lock. The good thing about a fair lock is that the waiting thread is not starved, but less efficient. Fair locks are strictly in accordance with the lock order to obtain the lock. A non-fair lock can be preempted. But it will import some threads that require locks to die.
Here is the source code for Reentrantlock:
Import Java.util.concurrent.timeunit;import Java.util.concurrent.locks.reentrantlock;public class Reentrantlockdemo {Reentrantlock lock = new Reentrantlock ();p ublic void Reentrantlockdemodemo () {System.out.println (" The state of the Lock: "+ Lock.trylock ()"), if (Lock.trylock ()) {System.out.println ("method is locked"), and try {System.out.println ("method Execution"); TimeUnit.SECONDS.sleep (3);} catch (Interruptedexception e) {e.printstacktrace ();} Finally{lock.unlock (); SYSTEM.OUT.PRINTLN ("Lock is released");}} else {System.out.println ("not executed");}} public void Test1 () {Thread thread = new Thread () {public void run () {Reentrantlockdemodemo ();}}; Thread.Start ();} public static void Main (string[] args) {Reentrantlockdemo rld = new Reentrantlockdemo (); Rld.test1 ();//reentrantlockdemo Rld2 = new Reentrantlockdemo (); Rld.test1 ();}}
Reentrantlock in Java