Android multithreaded Research (9)--read/write lock

Source: Internet
Author: User

One, what is the lock

There are interfaces and classes for locks under the Java Util.concurrent.locks package as follows:


Look at the code first:

Package Com.codeing.snail.test;public class Readwritelocktest {public static void main (string[] args) {final Output OUTPU t = new Output (), new Thread () {public void run () {while (true) {output.output ("Codeingsnail");}};}. Start (); new Thread () {public void run () {while (true) {Output.output ("Sunshine Cockroach");}};}. Start ();} Static class Output{public void Output (String name) {char[] Arry = Name.tochararray (); for (int i = 0; i < arry.length; i+ +) {System.out.print (arry[i]);} System.out.println ();}}}

The results of the output are as follows:

If we want the "Codeingsnail" and "Sun cockroach" two strings to be fully output, you need to use the Synchronized keyword to output a partial declaration, as follows:

Public synchronized void output (String name) {char[] Arry = Name.tochararray (), for (int i = 0; i < arry.length; i++) {Syst Em.out.print (Arry[i]);} System.out.println ();}

In fact, in addition to the Synchronized keyword, you can also use locks to achieve synchronization.

Reentrantlock lock = new Reentrantlock ();p ublic void output (String name) {lock.lock (); try{char[] Arry = Name.tochararray ( ); for (int i = 0; i < arry.length; i++) {System.out.print (arry[i]);} System.out.println ();} Finally{lock.unlock ();}}
The above code uses the Try...finally statement block to prevent an exception from being executed without the Unlock method, Reentrantlock is the implementation class of lock, the role of lock is similar to synchronized, but more object-oriented, To implement synchronization, you must use the same lock object.

Second, what is read-write lock read-write lock, divided into read lock and write lock, multiple read lock is not mutually exclusive, read lock and write lock mutex, write lock and write lock mutex. Let's take a look at an example of a buffer in the API documentation:

Class Cacheddata {Object data;volatile boolean cachevalid;final reentrantreadwritelock rwl = new Reentrantreadwritelock ( ); void Processcacheddata () {     rwl.readlock (). Lock ();     if (!cachevalid) {        //must release read lock before acquiring write lock        rwl.readlock (). Unlock ();        Rwl.writelock (). Lock ();        try {          //recheck state because another thread might has          //acquired write lock and changed state before we did.
   if (!cachevalid) {            data = ...            Cachevalid = true;          }          Downgrade by acquiring read lock before releasing write lock          Rwl.readlock (). Lock ();        } finally {          Rwl.wri Telock (). Unlock (); Unlock write, still hold read        }     }     try {use       data;     } finally {       rwl.readlock (). Unlock ( );     }     }}
If there are multiple threads reading the data, the first thread comes in with a write lock to write the data (the read lock is released first), the write lock is downgraded to a read lock (line 15th) after the write is completed, and the other threads do not affect each other while reading the data. This can improve read efficiency.



Android multithreaded Research (9)--read/write lock

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.