Reentrantlock in Java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.