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