Java Multithreading: "Juc lock" 02 of the Mutual exclusion lock Reentrantlock

Source: Internet
Author: User
Tags final int size printf thread

Reentrantlock Introduction

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

As the name suggests, Reentrantlock locks can only be held by a single thread lock at one point in time, and reentrant means that reentrantlock locks can be acquired multiple times by individual threads.

Reentrantlock is divided into "fair lock" and "unjust lock". Their differences are reflected in the fairness of the mechanism for acquiring locks. "Lock" is to protect competitive resources, prevent multiple threads to manipulate threads simultaneously error, reentrantlock at the same point in time can only be obtained by one thread (when a thread acquires "lock", other threads must wait) Reentraantlock is managed by a FIFO wait queue to acquire all threads of the lock. Under the "fair lock" mechanism, threads queue to acquire locks, and "unjust locks" acquire locks when the lock is in a accessible state, regardless of whether they are at the beginning of the queue.

Reentrantlock Function List

Create a Reentrantlock, default is "unjust lock". Reentrantlock ()///Create policy is fair's reentrantlock.
Fair to TRUE indicates a fair lock, and fair to false is a fair lock.
Reentrantlock (Boolean Fair)//query the number of times the current thread holds this lock.
int Getholdcount ()//returns the thread that currently owns this lock, and returns NULL if the lock is not owned by any thread.
Protected thread GetOwner ()//Returns a collection that contains threads that may be waiting to acquire this lock.
Protected collection<thread> getqueuedthreads ()//Returns the number of thread estimates that are waiting to get this lock.
int getqueuelength ()//Returns a collection that contains those threads that may be waiting for a given condition associated with this lock.
Protected collection<thread> getwaitingthreads (Condition Condition)//Returns the thread estimate waiting for the given condition associated with this lock.
int Getwaitqueuelength (Condition Condition)//query whether a given thread is waiting to acquire this lock.
Boolean hasqueuedthread (thread thread)//query If some threads are waiting to acquire this lock.
Boolean hasqueuedthreads ()//query whether some threads are waiting for the given condition associated with this lock.
Boolean haswaiters (Condition Condition)//If the fair lock returns True, False is returned.
Boolean Isfair ()//queries whether the current thread maintains this lock.
Boolean isheldbycurrentthread ()//query Whether this lock is persisted by any thread.
Boolean islocked ()//Acquire lock.
void lock ()//If the current thread is not interrupted, acquire the lock.
void lockinterruptibly ()//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.
Boolean trylock ()//If the lock is not persisted by another thread within the given wait time, and the current thread is not interrupted, the lock is acquired.
Boolean Trylock (long timeout, timeunit unit)//attempting to release this lock. void Unlock ()

Reentrantlock sample

By comparing "Example 1" and "Example 2", we can clearly understand the role of lock and unlock

Example 1

Import Java.util.concurrent.locks.Lock;
     
Import Java.util.concurrent.locks.ReentrantLock;        Locktest1.java//Warehouse class Depot {private int size;        The actual number of warehouses private lock lock;
        Exclusive lock Public Depot () {this.size = 0;
    This.lock = new Reentrantlock ();
        public void produce (int val) {lock.lock ();
            try {size = val;
        System.out.printf ("%s produce (%d)--> size=%d\n", Thread.CurrentThread (). GetName (), Val, size);
        finally {Lock.unlock ();
        } public void consume (int val) {lock.lock ();
            try {size = val;
        System.out.printf ("%s consume (%d) <--size=%d\n", Thread.CurrentThread (). GetName (), Val, size);
        finally {Lock.unlock (); 
     
}
    }
};
         
    Producer class Producer {private Depot Depot; Public Producer (Depot DepoT) {this.depot = depot;
    //Consumer Products: Create a new thread to produce the product in the warehouse. public void produce (final int val) {new Thread () {public void run () {Depot.produce (
            Val);
    }}.start ();
         
    }//Consumer class Customer {private Depot Depot;
    Public Customer (Depot Depot) {this.depot = Depot;
    //Consumer Products: Create a new thread to consume the product from the warehouse. public void consume (final int val) {new Thread () {public void run () {Depot.consume (
            Val);
    }}.start ();
        } public class LockTest1 {public static void main (string[] args) {Depot mdepot = new Depot ();
        Producer Mpro = new Producer (mdepot);
     
        Customer MCUs = new Customer (mdepot);
        Mpro.produce (60);
        Mpro.produce (120);
        Mcus.consume (90);
        Mcus.consume (150);
    Mpro.produce (110); }
}

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.