Java multithreaded Reentrantlock

Source: Internet
Author: User

This chapter is a basic introduction to the Reentrantlock package, this chapter mainly on the Reentrantlock of the general introduction, the content includes:
Reentrantlock Introduction
List of Reentrantlock functions
Reentrantlock Example
In the following two chapters, the implementation principles of the two subclasses (fair and unfair locks) of Reentrantlock are introduced respectively.
Reprint Please specify source: http://www.cnblogs.com/skywang12345/p/3496101.html

Reentrantlock Introduction

Reentrantlock is a reentrant mutex, also known as an "exclusive lock."

As the name implies, Reentrantlock locks can only be held by a single thread lock at the same point in time, whereas reentrant means that reentrantlock locks can be obtained multiple times by individual threads.
Reentrantlock is divided into " fair lock " and " non-fair lock ". The difference between them is fair in the mechanism of acquiring locks. "Locks" are designed to protect competing resources, prevent multiple threads from manipulating threads simultaneously, and reentrantlock can only be fetched by one thread at a time (when a thread acquires a "lock", other threads must wait). The Reentraantlock is a FIFO waiting queue to manage all threads that acquire the lock. Under the mechanism of "fair lock", threads queue to acquire the lock, while the "unfair lock" acquires the lock at the beginning of the queue, regardless of whether the lock is in the acquired state.

List of Reentrantlock functions
//creates a reentrantlock, which by default is an "unfair lock." Reentrantlock ()//creating a policy is the reentrantlock of fair. Fair is true to indicate a fair lock, and fair to false to indicate a non-fair lock. Reentrantlock (BooleanFair)//query the number of times that the current thread has retained this lock. intGetholdcount ()//returns the thread that currently owns this lock, or null if the lock is not owned by any thread. protectedThread GetOwner ()//returns a collection that contains the thread that may be waiting to acquire this lock. protectedCollection<thread>getqueuedthreads ()//returns the estimated number of threads that are waiting to acquire this lock. intgetqueuelength ()//returns a collection that contains those threads that may be waiting for a given condition related to this lock. protectedCollection<thread>getwaitingthreads (Condition Condition)//returns the number of thread estimates waiting for the given condition associated with this lock. intgetwaitqueuelength (Condition Condition)//queries whether a given thread is waiting to acquire this lock. Booleanhasqueuedthread (thread thread)//query whether some threads are waiting to acquire this lock. Booleanhasqueuedthreads ()//query whether some threads are waiting for a given condition related to this lock. Booleanhaswaiters (Condition Condition)//If "Fair lock" returns True, False is returned. BooleanIsfair ()//queries whether the current thread holds this lock. BooleanIsheldbycurrentthread ()//queries Whether this lock is persisted by any thread. BooleanisLocked ()//gets the lock. voidLock ()//Gets the lock if the current thread is not interrupted. voidlockinterruptibly ()//returns the Condition instance used with this Lock instance. Condition newcondition ()//the lock is acquired only if the lock is not persisted by another thread at the time of the call. BooleanTrylock ()//If the lock is not persisted by another thread within a given wait time and the current thread is not interrupted, the lock is acquired. BooleanTrylock (LongTimeout, timeunit unit)//An attempt was made to release this lock. voidUnlock ()

A reentrant lock refers to a lock that can be re-entered in the same thread. Of course, when the thread obtains the lock, the other thread waits for the lock to be released before the lock can be obtained.

Constructor: Reentrantlock (Boolean Fair): Boolean to indicate whether the lock created is a fair lock or a free-competition lock. The so-called fair lock refers to the order in which each desired thread obtains the lock, whether it is obtained in the order of arrival or free competition.

The usual way to use:

New // Not a fair lock Lock.lock (); Try {    //  synchronized do somethingfinally  {    lock.unlock () ;}

A typical example: Test the reentrant feature of a reentrant lock first, then create 3 threads, after each thread starts, tries to acquire the lock, acquires the lock on the shared data + 1, and then displays the Chula

 PackageBase2;ImportJava.util.Calendar;ImportJava.util.concurrent.locks.ReentrantLock; Public classTestlock {PrivateReentrantlock lock =NULL; //shared data for thread-synchronized access     Public intdata = 100;  PublicTestlock () {//Create a free-competition, re-entry lockLock =NewReentrantlock (); }     Public Static voidMain (string[] args) {Testlock tester=NewTestlock (); //test reentrant, Function Testreentry () in the same thread, can be repeated acquisition of locks, after the acquisition of locks, the function of displaying informationTester.testreentry (); //can be executed here without blocking, indicating that the lock can be re-enteredTester.testreentry (); //Re- EnterTester.testreentry (); //releases the lock for the re-entry test, which is unlocked by the number of re-entry, otherwise the lock cannot be acquired by another thread. tester.getlock (). Unlock ();        Tester.getlock (). Unlock ();        Tester.getlock (). Unlock (); //start 3 threads to test access to shared data under lock protectiontester.test (); }     PublicReentrantlock Getlock () {returnlock; }     Public voidTest () {NewThread (NewWorkerthread ( This) . Start (); NewThread (NewWorkerthread ( This) . Start (); NewThread (NewWorkerthread ( This) . Start (); }     Public voidTestreentry () {lock.lock (); Calendar Now=calendar.getinstance (); System.out.println (Now.gettime ()+ " " +Thread.CurrentThread ()+ "get lock."); }    //methods that are called by threads     Public voidTestRun ()throwsException {//LockingLock.lock (); Calendar Now=calendar.getinstance (); Try {            //Gets the current time value of the current calling thread shared data after the lock (and makes shared data + 1)System.out.println (Now.gettime () + "" +Thread.CurrentThread ()+ "accesses the data" + data++); //simulate other processing, here's a hypothetical sleep.Thread.Sleep (500); } Catch(Exception e) {e.printstacktrace (); } finally {            //UnlockLock.unlock (); }    }}//worker threads, calling Testserver.testrunclassWorkerthreadImplementsRunnable {PrivateTestlock tester =NULL;  Publicworkerthread (Testlock testlock) { This. Tester =Testlock; }     Public voidrun () {//Loop call, try to lock, and share the data +1, and then show it         while(true) {            Try {                //call Tester.testrun ()Tester.testrun (); } Catch(Exception e) {e.printstacktrace (); }        }    }}

Java multithreaded Reentrantlock

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.