Using synchronized to implement a lock code explanation

Source: Internet
Author: User
This article introduces you how to use synchronized to implement a lock code, the following is the actual case, the need for friends can refer to a reference.

Way One:

Public synchronized void A () {  //todo}


Way two:

public void B () {  synchronized (this) {    //todo  }}


In both of these ways, locks are added between {}, and we'll look at how lock is done:

public void C () {  lock.lock ();  try {    //TODO  } finally {    lock.unlock ();}  }


The lock in this way is added between lock () and unlock (), so to implement a lock function, you will want to implement such two methods, the lock () and the Unlock () method, first define a framework as follows:

public void Lock () {}public void unlock () {}


Then how to use synchronized to achieve these two methods.

Now actually just a little clear a little bit of thought, but still do not know how to fill these two methods, this is after the analysis of the lock locking what features, and then look at this code:

public void C () {    lock.lock ();    When current thread get the lock, and other thread have to wait    for try {        //current thread get in the lock, and other thread Can not get in        //TODO    }    finally {        lock.unlock ();        Current thread release the Lock    }}


This code I just added a little comment, nothing else to do, is not to help understand this code, to see what the most frequently occurring words are, is currentthread, then we go to fill lock () and unlock () method is not the time to pay attention to seize currentthread this keyword can find a solution? The answer is yes.

Then, how do you get threads to wait when using synchronized? is to use the Wait () method. How to get the thread to wake up is to use the Notify () method. Then use the wait () method in the lock () method to use the Notify () method in the Unlock () method. So we have a condition when we use Wait () and notify (), think about what we should use as a condition?

We should use the current lock whether it is occupied as a condition of judgment, if the lock is occupied, CurrentThread wait, think we use the synchronized is not always used this condition, the answer is also affirmative.

Then analyze when to release the lock, what to use as a condition, think if thread A gets the lock, can thread B be released? Of course not, if B can release it violates the principle, of course not. Must be a-thread lock can only be released by a. So judging the condition is to determine whether the thread holding the lock is CurrentThread, if it is, can be released, not the words of course not.

Now look at the full code:

Package Test.lock;import Java.util.random;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.threadfactory;public class NaiveLock {private static    Final long NONE =-1;    Private long owner = NONE;    Private Boolean islooked () {return owner! = NONE;        Public synchronized void Lock () {Long currentthreadid = Thread.CurrentThread (). GetId ();        if (owner = = currentthreadid) {throw new IllegalStateException ("Lock have been acquired by current thread"); } while (this.islooked ()) {System.out.println (String.Format ("thread%s was waitting lock", current            THREADID));            try {wait ();            } catch (Interruptedexception e) {e.printstacktrace ();        }} owner = Currentthreadid;    System.out.println (String.Format ("Lock is acquired by thread%s", owner)); } public synchronized void Unlock () {        if (!this.islooked () | | owner! = thread.currentthread (). GetId ()) {throw new IllegalStateException ("Onl        Y lock owner can unlock the lock ");        } System.out.println (String.Format ("Thread%s is unlocking", owner));        System.out.println ();        Owner = NONE;    Notify ();        } public static void Main (string[] args) {final Naivelock lock = new Naivelock (); Executorservice executor = Executors.newfixedthreadpool (new Threadfactory () {private Threadgroup group = n            EW threadgroup ("Test thread Group");            {Group.setdaemon (true);            } @Override Public Thread Newthread (Runnable r) {return new Thread (group, R);        }        }        );                        for (int i = 0; i < i++) {Executor.submit (new Runnable () {@Override                    public void Run () {lock.lock (); System.ouT.println (String.Format ("thread%s is running ...", Thread.CurrentThread (). GetId ()));                    try {thread.sleep (New Random (). Nextint (1000));                    } catch (Interruptedexception e) {e.printstacktrace ();                } lock.unlock ();        }            }            ); }    }}


Run a look at the results:

Lock is acquired by thread 8thread 8 is Running...thread waitting lockthread-is waitting lockthread  G Lockthread waitting Lockthread is waitting lockthread are waitting lockthread is waitting lockthread Waitting lockthread waitting Lockthread is waitting lockthread-is waitting lockthread-is waitting Lockthre Ad waitting Lockthread is waitting lockthread, waitting lockthread is waitting lockthread Lockthread waitting lockthread 9 is waitting lockthread 8 is unlocking Lock are acquired by thread 27thread are RU Nning...thread unlocking Lock is acquired by thread 26thread are running...thread are unlocking lock is Acquir Ed by thread 25thread are running...thread unlocking Lock is acquired by thread 24thread are Running...thread 2 4 is unlocking Lock are acquired by thread 23thread are running...thread are unlocking Lock are acquired by thread 22t Hread is running...thRead is unlocking lock are acquired by thread 21thread are Running...thread is unlocking lock are acquired by thre Ad 20thread is running...thread unlocking Lock are acquired by thread 19thread are Running...thread unloc King Lock is acquired by thread 18thread are Running...thread is unlocking Lock are acquired by thread 17thread s running...thread is unlocking lock are acquired by thread 16thread are running...thread and are unlocking lock is AC quired by thread 15thread are running...thread unlocking Lock are acquired by thread 14thread-is Running...thre  Ad unlocking lock is acquired by thread 13thread Running...thread are unlocking lock is acquired by thread 12thread is Running...thread unlocking Lock are acquired by thread 11thread one is Running...thread one is Unlocki Ng Lock is acquired by thread 10thread are running...thread unlocking Lock are acquired by thread 9thread 9 is RU Nning...thread 9 is Unlocking 


If you change the for loop to 30 times, look at the results:

Lock is acquired by thread 8thread 8 is Running...thread waitting lockthread-is waitting lockthread  G Lockthread waitting Lockthread is waitting lockthread are waitting lockthread is waitting lockthread Waitting lockthread waitting Lockthread is waitting lockthread-is waitting lockthread-is waitting Lockthre Ad waitting Lockthread is waitting lockthread, waitting lockthread is waitting lockthread Lockthread waitting lockthread 9 is waitting lockthread 8 is unlocking Lock are acquired by thread 27thread are RU Nning...thread 8 is waitting lockthread are unlocking Lock is acquired by thread 27thread are Running...thread Waitting Lockthread is unlocking Lock are acquired by thread 27thread is Running...thread waitting Unlocking Lock is acquired by thread 24thread are running...thread are waitting lockthread is unlocking Loc K is acquired by thread23thread running...thread waitting Lockthread is unlocking Lock are acquired by thread 22thread are Runni Ng...thread is waitting lockthread are unlocking Lock is acquired by thread 22thread are Running...thread  Itting Lockthread Unlocking Lock is acquired by thread 22thread are Running...thread 22 Is unlocking Lock are acquired by thread 22thread are running...thread waitting lockthread is unlocking lock is acquired by thread 22thread are running...thread waitting lockthread is unlocking Lock are acquired by Threa D 17thread is running...thread unlocking Lock are acquired by thread 16thread are Running...thread is unlock  ING Lock is acquired by thread 15thread are running...thread unlocking Lock are acquired by thread 14thread Running...thread unlocking Lock is acquired by thread 13thread are running...thread are unlocking lock is Acq Uired by Thread 12thread Running...thread Unlocking Lock is a acquired by thread 11thread one is running...thread one is unlocking lock are acquired by thread 10thread are running...thread unlocking Lock are acquired by thread 9thread 9 are running...t Hread 9 is unlocking lock are acquired by thread 8thread 8 are running...thread 8 is unlocking lock are acquired by thread 26thread is Running...thread unlocking Lock are acquired by thread 25thread are Running...thread is Unlockin G Lock is acquired by thread 27thread are running...thread unlocking Lock is acquired by thread 24thread Unning...thread unlocking Lock is acquired by thread 23thread are running...thread are unlocking lock is Acqui Red by thread 21thread Running...thread are unlocking Lock are acquired by thread 20thread-is Running...thread Unlocking lock is acquired by thread 19thread are running...thread unlocking lock is acquired by thread 18 Thread is running...tHread is unlocking 


Believe that you have seen these cases you have mastered the method, more wonderful please pay attention to the PHP Chinese network other related articles!

Related reading:

How PHP implements the stack data structure and the code example of the brace matching algorithm

The simplest string matching algorithm in PHP, PHP matching algorithm _php tutorial

The simplest tutorial for string matching algorithms in PHP

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.