Java Multithreading Series (iv)

Source: Internet
Author: User

Use of lock

Preface: This series will start from the beginning of the Java multithreading related technology, the content of the "Java Multithreading Core technology" and "Java Concurrency Programming Practical" and other related information, hope to stand on the shoulders of giants, and then through my understanding can make knowledge more simple and understandable.

Directory
    • Understanding CPUs, cores, and threads
    • Java multithreaded Series (i) Java multithreading skills
    • Concurrent access to object variables of the Java Multithreaded Series (ii)
    • Java Multi-threaded series (three) of the waiting notification mechanism
    • The use of Reentrantlock in Java Multithreading series (iv)
Reentrantlock (re-entry Lock)
public class MyService {    private Lock lock = new ReentrantLock();    public void testMethod() {        lock.lock();        for (int i = 0; i < 5; i++) {            System.out.println("ThreadName=" + Thread.currentThread().getName()                    + (" " + (i + 1)));        }        lock.unlock();    }}

Effect and synchronized, can be executed synchronously, lock method get lock, unlock method release lock

Await method
public class MyService {    private Lock lock = new ReentrantLock();    private Condition condition=lock.newCondition();    public void testMethod() {                try {            lock.lock();            System.out.println("开始wait");            condition.await();            for (int i = 0; i < 5; i++) {                System.out.println("ThreadName=" + Thread.currentThread().getName()                        + (" " + (i + 1)));            }        } catch (InterruptedException e) {            // TODO 自动生成的 catch 块            e.printStackTrace();        }        finally        {            lock.unlock();        }    }}
    • By creating a condition object to make the thread wait, you must first execute the Lock.lock method to obtain the lock
Signal method
public void signal()    {        try        {            lock.lock();            condition.signal();        }        finally        {            lock.unlock();        }    }
    • The signal method of the condition object can wake the wait thread
Create multiple Condition objects
    • The signal (Signalall) method of a Condition object corresponds to one by one of the object's await method, That is, the signal (Signalall) method of a condition object cannot wake the await method of another condition object
    • The Reentrantlock class can wake a thread that specifies a condition, and the wake of object is random
Condition class and Object class
    • The Awiat method of the condition class is equivalent to the wait method of the object class
    • The signal method of the condition class is equivalent to the Notify method of the object class
    • The Signalall method of the condition class is equivalent to the Notifyall method of the object class
Lock's Fair lock and non-fair lock
Lock lock=new ReentrantLock(true);//公平锁Lock lock=new ReentrantLock(false);//非公平锁
    • Fair locking refers to the order in which threads acquire locks in the order in which they are locked, while non-fair locks refer to the locking mechanism, in which the first lock thread is not necessarily the first to acquire the lock.
Methods of the Reentrantlock class
    • Getholdcount () queries the number of times the current thread holds this lock, that is, the number of times that this thread executes the lock method
    • Getqueuelength () returns the estimated number of threads that are waiting to acquire this lock, such as starting 10 threads, 1 threads acquiring locks, and returning 9
    • Getwaitqueuelength (Condition Condition) returns the number of thread estimates waiting for the given condition associated with this lock. For example, 10 threads, using the same condition object, and 10 threads executing the await method of the condition object at this time, this method is executed to return 10
    • Haswaiters (Condition Condition) queries whether a thread waits for a given condition associated with this lock (Condition), for the specified Contidion object, how many threads have performed the Condition.await method
    • Hasqueuedthread (thread thread) queries whether a given thread is waiting to acquire this lock
    • Hasqueuedthreads () Whether the thread waits for this lock
    • Isfair () Whether the lock is a fair lock
    • Isheldbycurrentthread () whether the current thread remains locked, the thread's execution lock method is false and true before and after
    • Islock () Whether this lock is occupied by any thread
    • Lockinterruptibly () Gets the lock if the current thread is not interrupted
    • Trylock () attempts to acquire a lock, only when the lock is not occupied by the thread at the time of the call, to obtain the lock
    • Trylock (Long timeout timeunit unit) acquires a lock if it is not persisted by another thread within a given wait time
The difference between Trylock and lock and lockinterruptibly
    • Trylock can obtain a lock to return true, cannot immediately return False,trylock (Long timeout,timeunit unit), can increase the time limit, if more than the time period has not acquired the lock, return false
    • Lock can obtain a lock to return true, cannot wait to obtain a lock
    • Lock and lockinterruptibly, if two threads execute the two methods separately, but break these two threads at this time, the former will not throw an exception, the latter will throw an exception
Read/write Lock
    • Reentrantlock are completely mutually exclusive, so the efficiency is not high.
public void read() {        try {            try {                lock.readLock().lock();                System.out.println("获得读锁" + Thread.currentThread().getName()                        + " " + System.currentTimeMillis());                Thread.sleep(10000);            } finally {                lock.readLock().unlock();            }        } catch (InterruptedException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }
    • Read locks, at which time multiple threads can or have read locks
public void write() {        try {            try {                lock.writeLock().lock();                System.out.println("获得写锁" + Thread.currentThread().getName()                        + " " + System.currentTimeMillis());                Thread.sleep(10000);            } finally {                lock.writeLock().unlock();            }        } catch (InterruptedException e) {            e.printStackTrace();        }    }
    • Write lock, at which time only one thread can get a write lock
public void read() {        try {            try {                lock.readLock().lock();                System.out.println("获得读锁" + Thread.currentThread().getName()                        + " " + System.currentTimeMillis());                Thread.sleep(10000);            } finally {                lock.readLock().unlock();            }        } catch (InterruptedException e) {            e.printStackTrace();        }    }    public void write() {        try {            try {                lock.writeLock().lock();                System.out.println("获得写锁" + Thread.currentThread().getName()                        + " " + System.currentTimeMillis());                Thread.sleep(10000);            } finally {                lock.writeLock().unlock();            }        } catch (InterruptedException e) {            e.printStackTrace();        }    }
    • The result is a write lock is performed after the read lock is released, which means that the read and write locks are mutually exclusive
Summarize
    • The lock class can also implement thread synchronization, while lock obtains a lock that requires the lock method to be executed, and the unlock method is required to release the lock
    • The lock class can create condition objects, condition objects are used to thread wait and wake threads, and it is important to note that the condition object wakes up the thread that executes the await method with the same condition, so it can implement the thread that wakes the specified class
    • Lock class Fair lock and unfair lock, the fair lock is in the order of locking, the unfair lock is not in order, that is, the lock method is not the first to obtain the lock
    • Lock class has read lock and write lock, read share, write mutex, read-write Mutex
I think sharing is a kind of spirit, sharing is my pleasure, not to say I think I said must be right, I said may be a lot of wrong, but I hope I said something is my life experience and thinking, is to give a lot of people to reflect on, maybe give you a second, half a second, even if a word a little bit of truth, triggered their This is my greatest value. (This is my favorite word, but also I write the original intention of the blog)

Java Multithreading Series (iv)

Related Article

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.