Java-lock article

Source: Internet
Author: User

1.Lock

Lock is an interface under the Java.util.concurrent.locks package, and thelock implementation provides more than the use of synchronized methods and statements to obtain

More extensive locking operations that can handle thread synchronization issues in a more elegant way.

The implementation classes are: Reentrantlock, Reentrantreadwritelock.readlock,reentrantreadwritelock.writelock

Note: A sychronized-modified method or block of statements is automatically released after the code is executed, and lock is required to manually release the locks.

So in order to ensure that the lock is finally released (in case of abnormal conditions), the mutex is placed in the try and the release lock is placed in the finally.

//the basic use of Lockdemo,//Reentrantlock,reentrantreadwritelock (Read and write lock) under lock interface//using the demo/*Lock l= ...; L.lock ();//Start locking try{...//Here is the sync block} finally{l.unlock ();//Unlocking the lock is not like synchronized, lock must be unlocked manually}*/ImportJava.util.concurrent.locks.ReentrantLock; Public classlockdemo{ Public Static voidMain (String []args) {outputer op=NewOutputer (); NewThread (OP). Start (); NewThread (OP). Start (); NewThread (OP). Start (); }} classOutputerImplementsrunnable{PrivateReentrantlock l=NewReentrantlock ();  Public voidrun () {l.lock (); Try{            for(inti=0;i<3;i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "i=" +i); }                  }       finally{l.unlock (); }        }}

2.ReadWriteLock

We will have a need to read and write data, in order to ensure the consistency and integrity of the data, the need for reading and writing is mutually exclusive, write and write

is mutually exclusive, but reads and reads do not need to be mutually exclusive, so read and read not mutually exclusive performance is higher, to look at the code prototype that does not consider mutually exclusive case:

 Public classReadwritelocktest { Public Static voidMain (string[] args) {FinalData data =NewData ();  for(inti = 0; I < 3; i++) {              NewThread (NewRunnable () { Public voidrun () { for(intj = 0; J < 5; J + +) {Data.set (NewRandom (). Nextint (30));          }}). Start (); }                  for(inti = 0; I < 3; i++) {              NewThread (NewRunnable () { Public voidrun () { for(intj = 0; J < 5; J + +) {data.get ();          }}). Start (); }      }  }  classData {Private intData//Sharing Data     Public voidSetintdata) {System.out.println (Thread.CurrentThread (). GetName ()+ "Ready to write Data"); Try{Thread.Sleep (20); } Catch(interruptedexception e) {e.printstacktrace (); }           This. data =data; System.out.println (Thread.CurrentThread (). GetName ()+ "Write" + This. Data); }          Public voidget () {System.out.println (Thread.CurrentThread (). GetName ()+ "ready to read Data"); Try{Thread.Sleep (20); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "read" + This. Data); }  }  

Output Result:

thread-1 Preparing to write data  thread-3 preparing to read data  thread-2 preparing to write data  thread-0 preparing to write data  Thread-4 ready to read data  thread-5 ready to read data  thread-2 write to  thread-  4 Read  thread-5 read 5  thread-1 Write 12  

We want to implement write and write mutexes, read and write mutexes, read and read mutexes, and add sychronized modifiers to the set and get methods:

 Public synchronized void Set (int  data) {...}        Public synchronized void get () {...}  

Output Result:

thread-0 Prepare to write data  thread-0 Write 9  thread-5 prepare to read data  thread-5 Read 9  Thread-5 ready to read data  thread-5 read 9  thread-5 ready to read data  thread- 5 Read 9  Thread-5 ready to read data  thread

We found that while the write and write mutex, read and write are mutually exclusive, but also mutually exclusive between read and read, can not be executed concurrently, more efficient

Low, use the read-write lock implementation code as follows:

classData {Private intData//Sharing Data    PrivateReadwritelock RWL =NewReentrantreadwritelock ();  Public voidSetintdata) {Rwl.writelock (). Lock ();//take a write lock        Try{System.out.println (Thread.CurrentThread (). GetName ()+ "Ready to write Data"); Try{Thread.Sleep (20); } Catch(interruptedexception e) {e.printstacktrace (); }               This. data =data; System.out.println (Thread.CurrentThread (). GetName ()+ "Write" + This. Data); } finally{rwl.writelock (). Unlock ();//Release Write lock        }      }          Public voidget () {Rwl.readlock (). Lock ();//fetch to read lock        Try{System.out.println (Thread.CurrentThread (). GetName ()+ "ready to read Data"); Try{Thread.Sleep (20); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName ()+ "read" + This. Data); } finally{rwl.readlock (). Unlock ();//Release read lock        }      }  }  

Output Result:

thread-4 ready to read data  thread-3 ready to  readdata thread-5 ready to read data  thread-5 Read  Thread-4 Read  thread-3 Read  thread-2 ready to write data  thread-2 Write 6  Thread-2 preparing to write data  thread-2 write ten  thread-1 prepare to write data  thread- 1 Write  Thread

Java-lock 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.