Use instances of synchronized in Java

Source: Internet
Author: User

First, the use of the scene

In charge of background development. Very often the interface is provided to the front-end developer to invoke, and this scenario is encountered:

Need to provide a bonus interface. Each username can only be collected once, and we can save the successful recipients in the database with a tag. If the user comes back to collect, query the database to see if the user has been picked up.

But the problem is, if the user is very fast hand speed. Two times in a very short period of time the award button (the front-end is not controlled, we can not rely on the front-end control).

Then may have lost two times the receiving interface, and it is possible to call the second time when querying the database, the first time the award has not been completed to update the prize tag.

This scenario can be used to synchronized

Ii. Examples of Use

Code:

 PackageCom.luo.test; Public  class syntest {     Public Static void Main(String args[])throwsinterruptedexception{syntest syntest =NewSyntest ();    Syntest.test (); } Public void Test()throwsinterruptedexception{NewSynThread1 (). Start ();NewSynThread1 (). Start (); } Public void syn(String userName)throwsException {synchronized(UserName) {System.out.println ("Enter the sync block. Username= "+ UserName); Thread.Sleep ( the);//5 secSystem.out.println ("Exit sync block, username="+ UserName); }} class SynThread1 extends Thread { Public void Run(){Try{SYN ("Luoguohui"); }Catch(Exception e)            {E.printstacktrace (); }        }    }}

Execution Result:

Judging from the results, you know. Synchronized works, and here the two SYN (String userName) method is called. The period is set to stay for 5 seconds, but still wait for the first time to execute. The second call was entered into the synchronized block.

In order to further confirm our if, we do not want to remove synchronized such as the following:

    publicvoidsyn(String userName) throws Exception {//      synchronized(userName) {            System.out.println("进入到同步块。userName=" + userName);            Thread.sleep(5000);  //5秒            System.out.println("退出同步块,userName=" + userName);//      }    }

Execution Result:

The control can be analyzed.

Use the method from the instance to see:

publicvoidsyn(String userName) throws Exception {    synchronized(userName) {        System.out.println("进入到同步块,userName=" + userName);        Thread.sleep(5000);  //5秒        System.out.println("退出同步块,userName=" + userName);    }}

Surround the code with synchronized.

Use instances of synchronized in Java

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.