Talk about lock lock __java in Java

Source: Internet
Author: User
Tags static class

In Java multithreading, you can use the keyword synchronized to implement a mutex between threads. After JDK1.5, a thread concurrency library java.util.concurrent is provided to manipulate multiple threads, including java.util.concurrent.atomic and Java.util.concurrent.lock. Atomic can realize the atomic operation of data or variable, and lock can achieve thread mutual exclusion, can realize read-write lock, same as synchronized belong to lock, but more flexible in use than synchronized.

In code, you can create a lock lock with the new Reentrantlock (), call Lock () to lock the code, and call Unlock () to unlock it. Of course, in order to ensure that the code can be abnormal when the operation of the unlock, should be locked code in a try wrapped, and in the finally unlocked, the specific code implementation is as follows:

public class Main {//static inner class implements thread sharing static class example{//create lock lock lock = new Reentrantlock ();
            public void OutPut (String str) {//Locked lock.lock ();
                try{for (int i=0;i<str.length (); i++) {System.out.print (Str.charat (i));
            } System.out.print ("\ n");
            }finally {//unlock lock.unlock ();
        }} public static void Main (string[] args) {final Example Example = new Example ();
                    New Thread (New Runnable () {@Override public void run () {while (true) {
                Example.output ("str1");
        }}). Start ();
                    New Thread (New Runnable () {@Override public void run () {while (true) {
                Example.output ("str2");
      }
            }  ). Start (); }
}

For lock read-write locks, you can obtain a read-write lock through the new Reentrantreadwritelock (). The so-called read-write lock, is the multithreading between the reading is not mutually exclusive, read and write mutually exclusive. Read-write lock is a spin lock, if there is no reader, there is no writer, then the writer can immediately acquire the lock, otherwise it must spin there, until there is no writer or reader. If no writer is present, the reader can immediately obtain the read-write lock, otherwise the reader must spin it there until the writer releases the lock. The specific code implementation is as follows:

public class Main {//static inner class implements thread sharing static class example{//create lock Reentrantreadwritelock lock = new
        Reentrantreadwritelock ();
            Read operation public void Read () {//Get read lock and Lock Lock.readlock (). Lock ();
                try{System.out.println ("read thread start");
                Thread.Sleep (1000);
            SYSTEM.OUT.PRINTLN ("Read thread End");
            }catch (Exception e) {e.printstacktrace ();
            }finally{//Unlock Lock.readlock (). Unlock ();
            //write operation public void write () {//Get write Lock and Lock Lock.writelock (). Lock ();
                try{System.out.println ("Write thread Start");
                Thread.Sleep (1000);
            System.out.println ("Write Thread End");
            }catch (Exception e) {e.printstacktrace ();
            }finally {//Unlock lock.writelock (). Unlock ();
 }
        }   public static void Main (string[] args) {final Example Example = new Example ();
                    New Thread (New Runnable () {@Override public void run () {while (true) {
                    Example.read ();
                Example.write ();
        }}). Start ();
                    New Thread (New Runnable () {@Override public void run () {while (true) {
                    Example.read ();
                Example.write ();
    }}). Start (); }
}

Run Result:


According to the results can be found, multi-threaded reentrantreadwritelock can be multithreaded simultaneously read, but write words at the same time only one thread execution.

Finally say a read and write lock application scenario, we can use read and write lock, but to achieve a multi-threaded data caching function, the specific realization of the following ideas:

Class datacatch{
    Object data;//Cached
    volatile Boolean Iscatch = false;//Cache
    Reentrantreadwritelock lock = new Reentrantreadwritelock (); Generate read-write lock public

    void process () {
        lock.readlock (). Lock ();//Read the lock first, at which time the data will not be modified
        //Data not cached
        if (!iscatch) {
            lock.readlock (). Unlock ()//Interpretation of Lock
            Lock.writelock (). Lock ();//write lock, data will not be read
            /********
             *
             * Performs a data query operation and assigns value to data
             *
             ********/
            iscatch = true;
            Lock.readlock (). Lock ();  Read the lock first and then write the lock
            Lock.writelock (). Lock ()
        ;
        /********
         * *
         put back the data to the user
         *
         ********/
        lock.readlock () Unlock ()//interpretation of the 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.