"Java concurrency" traditional thread mutex technology-synchronized

Source: Internet
Author: User
Tags mutex

When multiple threads operate the same resource at the same time, they will encounter concurrency problems, such as bank transfer, ticketing system, etc. To avoid these problems, we can use the Synchronized keyword to solve, the following for synchronized common usage to do a summary. First write a program that has concurrency problems, as follows:

 Public  class traditionalthreadsynchronized {     Public Static void Main(string[] args) {//cannot be an instance object of the new inner class in a static method        //private Outputer outputer = new Outputer ();        NewTraditionalthreadsynchronized (). Init (); }Private void Init() {FinalOutputer Outputer =NewOutputer ();//thread 1 print: Duoxiancheng        NewThread (NewRunnable () {@Override             Public void Run() { while(true) {Try{Thread.Sleep (5); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } outputer.output1 ("Duoxiancheng"); }}). Start ();;//Thread 2 print: Eson15        NewThread (NewRunnable () {@Override             Public void Run() { while(true) {Try{Thread.Sleep (5); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } outputer.output1 ("Eson15");    }}). Start ();; }StaticClass Outputer {//Customize a string printing method to print one character at a         Public void OUTPUT1(String name) {intLen = Name.length (); for(inti =0; i < Len;            i++) {System.out.print (Name.charat (i)); } System.out.println (""); }           }}

In the internal class Outputer defines a method of printing a string, one character of the printing, so it is easier to intuitively see concurrency problems, because the character sequence is scrambled to indicate that there is a problem. Then open two threads in the Init method, one thread prints "Duoxiancheng", and the other thread prints "eson15". Look at the results of the operation:

Eson15duoxianche
Ng
Eson15
Duoxiancheng
Duoxiancheng
Eson15
Esduoxiancheng
On15
Duoxiancheng

There has been a problem, in order to solve this problem, you can use the Synchronized synchronous code block to synchronize the common part, but need to give it a lock, this lock is an object, can be any object, but the premise is that two threads must be the same object lock can be used, That's good to understand. Then add the output1() synchronized code block to the method below:

static  class Outputer {private  String token = ;    //define a lock  public  void  OUTPUT1  (String name) {synchronized  (token) //any one object can be used as a parameter.            But the object is the same for two threads  //if the name is not used, because different threads come in name is not the same, not the same name  {            int  len = name.length (); for  (int  i = 0 ; i < Len; i++)            {System.out.print (Name.charat (i));             } System.out.println (); }    }}   

After the above transformation, the thread safety problem is basically solved, but can be further extended, if the method is added synchronized keyword, then what is this sync lock? Let's write another method in the Outputer class output2() :

StaticClass Outputer {PrivateString token ="";//define a lock     Public void OUTPUT1(String name) {synchronized(token)//Any object can be used as a parameter, but the object is the same for two threads.{intLen = Name.length (); for(inti =0; i < Len;            i++) {System.out.print (Name.charat (i)); } System.out.println (""); }    } Public synchronized void Output2(String name) {intLen = Name.length (); for(inti =0; i < Len;        i++) {System.out.print (Name.charat (i)); } System.out.println (""); }   }

Method internal implementation logic is exactly the same, the only difference is that synchronized is added to the method, then we let the init () method in the two threads, one call output1(String name) method, another call output2(String name) method, from the results can be seen, the thread security problem appears again. The cause of the problem is not difficult to find: now two methods are added synchronized, but two threads in the call two different methods or there is a problem, that is, or play each of the ... So the problem is in this lock, which means the two are not using the same lock!
If we output1() change the token of synchronized in the method to this, then it is no problem to run again, which means:when the synchronized keyword is modified, the synchronization lock is this, which is equivalent to the code block synchronized(this) {...} .
Further down, now write a static method in the Outputer class output3(String name) , and let synchronized modify the static method.

StaticClass Outputer {PrivateString token ="";//define a lock     Public void OUTPUT1(String name) {synchronized(token)//Any object can be used as a parameter, but the object is the same for two threads.{intLen = Name.length (); for(inti =0; i < Len;            i++) {System.out.print (Name.charat (i)); } System.out.println (""); }    } Public Static synchronized void OUTPUT3(String name) {intLen = Name.length (); for(inti =0; i < Len;        i++) {System.out.print (Name.charat (i)); } System.out.println (""); }       }}

Then one thread in the init () method calls the output1() method, and the other thread invokes the output3() method. There is no doubt that there is a thread-safety problem. But how to solve it? Because the static method is loaded when the class is loaded, the lock should be a byte-code object for the class. Then change the token to Outputer.class solve the problem, which means:when the synchronized keyword modifies the static method, the synchronization lock is the bytecode object of the class, which is equivalent to the code block synchronized(classname.class) {...} .
  
Finally, let's summarize:

  • the lock of the synchronization code block is any object . This lock is arbitrarily set whenever different threads are executing the same block of synchronization code.
  • The lock of the synchronization function is a fixed this. When synchronization is required with the logic in the synchronization function, the lock in the code block must be this.
  • The lock of a static synchronization function is the bytecode file object of the class to which the function belongs . The object can be this.getClass() obtained by means of a method, or it can be 当前类名.class represented.

-Willing to share and progress together!
-More articles please see: http://blog.csdn.net/eson_15

"Java concurrency" traditional thread mutex technology-synchronized

Related Article

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.