JAVA concurrency-Explicit lock (i) __java

Source: Internet
Author: User
In addition to providing built-in lock synchronized, the Java language provides advanced explicit lock locks as a functional supplement after JDK6. In most cases, built-in locks work well and we try to use built-in locks as much as possible. However, it must be admitted that there are some limitations to the built-in locks. For example, you cannot break a thread that is waiting to acquire a lock, cannot wait indefinitely while requesting a lock, and cannot implement non-blocking locking rules. Consider using an explicit lock when these advanced features are required in your program. Let's introduce 2 kinds of display locks, lock and Readwritelock.

The following is the definition of lock:
Public interface Lock {
    //acquire locks, infinite wait for
    void Lock () before getting lock;
    Obtain the lock, allowing the thread to be interrupted before the lock is obtained
    (lockinterruptibly () throws interruptedexception;
    Returns True, which represents success in obtaining a lock, returns False, a
    boolean trylock ()
    that represents a failure to acquire a lock; Returns True, which represents success in obtaining a lock within a specified time; returns False, which represents a failure to acquire a lock within a specified time
    boolean trylock (Long, timeunit) throws interruptedexception;
    Release lock
    void Unlock ();
    Returns an instance of the communication between threads, an introduction to the Condition interface, see Blog < conditional queue (ii) >
    Condition newcondition ();
}

Reentrantlock is a class that implements the lock interface, is a reentrant lock (blog "explicit Lock (II)" is described), below are some examples.
Lock () uses
class test{
	private Lock lock=new reentrantlock (); 
	public void Fun () {
		lock.lock ();
		try{
			
		}catch (Exception e) {
			
		}finally{
			lock.unlock ();
		}
	}
}

Trylock () uses
class test{
	private Lock lock=new reentrantlock ();
	public void Fun () {
		if (Lock.trylock ()) {
			try{
				
			}catch (Exception e) {
				
			}finally{
				lock.unlock () ;
			}
		} else{}}}

Lockinterruptibly () uses
class test{
	private Lock lock=new reentrantlock ();
	
	public void Fun () {
		try{
			lock.lockinterruptibly ();
			try{
				
			}catch (Exception e) {
				
			}finally{
				lock.unlock ();
			}
		} catch (Interruptedexception e) {
			//Throw exception or Resume Break}}}



The following is the definition of Readwritelock:
Public interface Readwritelock {
    Lock readlock ();
    Lock Writelock ();
}


The benefit of Readwritelock is the ability to make the read operation concurrent (i.e. allowing concurrent read, but must be mutually exclusive to read, write, write) under the premise of ensuring the security of the write operation. Reentrantreadwritelock is the class that implements the Readwritelock interface, using the following methods:
Import Java.util.concurrent.locks.Lock;
Import Java.util.concurrent.locks.ReentrantReadWriteLock; public class demo{public static void Main (String [] args) throws interruptedexception {final Test test = new
        Test ();
            New Thread () {public void run () {Test.get (Thread.CurrentThread ());
        };
         
        }.start ();
            New Thread () {public void run () {Test.get (Thread.CurrentThread ());
        };
	}.start ();
    Class Test {private Reentrantreadwritelock rwl = new Reentrantreadwritelock ();
    Private Lock rlock=rwl.readlock ();
    Private Lock wlock=rwl.writelock ();
        public void get (thread thread) {rlock.lock ();
            try {Long start = System.currenttimemillis ();
            while (System.currenttimemillis ()-start <=) {System.out.println (Thread.getname () + "reading operation in progress"); } System.out.println (Thread.getname ()+ "read operation completed");
        finally {Rlock.unlock (); }
    }
}


The difference between synchronized and lock:
1. Synchronized automatically releases locks, lock must be manually released in finally block
2. Lock can provide some advanced functions, such as: non-blocking lock, wait time response interrupt, infinite wait
3. Synchronized is a built-in lock, supported by the JVM; Lock is a Java language-level locking mechanism

4. Synchronized is a fair lock; lock defaults to a fair lock, but can be set to a fair lock.


The author opened a live, detailed introduction to Java from the beginning to the mastery of how to learn, what to learn.

For students who want to learn and improve their Java skills, welcome to https://www.zhihu.com/lives/932192204248682496

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.