A brief exploration of Java synchronized keywords

Source: Internet
Author: User
Tags mutex

Synchronized is a keyword that is used in Java multithreaded programming to serialize the operations between threads. This approach is similar to using exclusive locks in the database for concurrency control, but the difference is that data objects are locked in the database, while Java is locking the code that will be executed.

Here are a few things to keep in mind when using the Synchronized keyword in Java:

1.synchronized is a restriction on access to the same resource. This is the reason why the keyword appears.


2. For a class, when a thread executes into a synchronized-decorated class method or a code snippet in a class method, the method or code snippet is added to the mutex, and all the code snippets in the class using the synchronized-decorated class method or class method are added to the mutex. It does not affect a class method or a code snippet in a class method that does not use the synchronized adornment, and it does not affect the thread's execution of these remaining locked class methods or the code snippets in the class method, and any methods in other classes; When the thread finishes executing the synchronized These mutexes are freed at the same time after the code snippet in the decorated class method or class method.


3. For an object, when a thread executes into a synchronized-decorated object method or a code snippet in an object method, the case is the same as in 2.


4.3rd and 2nd have no effect on each other


5.synchronized () The content used in parentheses indicates whether the resource to be blocked is a class or a method or block of code in an object. Because the synchronized modifier cannot be used on a class declaration, it is necessary for a class to use a form similar to synchronized (Classname.class) {/*...*/} or using the synchronized-decorated class method

The instance code is as follows:

(1) Printer class

1  Public classPrinter {2      Public Static voidPrintA ()3     {4System.out.println (Thread.CurrentThread () + ": Invoke PrintA Method");5         synchronized(Printer.class)6         {7              for(inti = 0; I < 5; i++)8             {9System.out.println (Thread.CurrentThread () + ": Into PrintA method ' s loop ...");Ten                 Try One                 { AThread.Sleep (1000); -                 } -                 Catch(interruptedexception e) the                 { - e.printstacktrace (); -                 } -             } +         } -     } +      A      Public synchronized voidPRINTB () at     { -System.out.println (Thread.CurrentThread () + ": Invoke Printb Method"); -          for(inti = 0; I < 5; i++) -         { -System.out.println (Thread.CurrentThread () + ": Into Printb method ' s loop ..."); -             Try in             { -Thread.Sleep (1000); to             } +             Catch(interruptedexception e) -             { the e.printstacktrace (); *             } $         }Panax Notoginseng     } -}
View Code

(2) Threada class

1  Packagedemo;2 3  Public classThreadaextendsthread{4Printer p =NULL;5      PublicThreada (Printer p)6     {7         Super("Threada");8          This. P =p;9     }Ten      Public voidRun () One     { A         //P.printa (); - Printer.printa (); -     } the}
View Code

(3) Threadb class

1  Packagedemo;2 3  Public classThreadbextendsthread{4Printer p =NULL;5      Publicthreadb (Printer p)6     {7         Super("Threadb");8          This. P =p;9     }Ten      Public voidRun () One     { A         //p.printb (); - printer.printb (); -     } the}
View Code

(4) Mainthread class

1  Packagedemo;2 3  Public classMainthread {4      Public Static voidMain (string[] args)5     {6Printer p =NewPrinter ();7Threada TA =NewThreada (p);8THREADB TB =Newthreadb (p);9         Ten Ta.start (); One         Try { ATa.join (10); -}Catch(interruptedexception e) { -             //TODO auto-generated Catch block the e.printstacktrace (); -         } - Tb.start (); -     } +}
View Code

The results of the operation are as follows:

Thread[threada,5,main]: Invoke PrintA method
Thread[threada,5,main]: Into PrintA method ' s loop ...
Thread[threada,5,main]: Into PrintA method ' s loop ...
Thread[threada,5,main]: Into PrintA method ' s loop ...
Thread[threada,5,main]: Into PrintA method ' s loop ...
Thread[threada,5,main]: Into PrintA method ' s loop ...
Thread[threadb,5,main]: Invoke Printb method
Thread[threadb,5,main]: Into Printb method ' s loop ...
Thread[threadb,5,main]: Into Printb method ' s loop ...
Thread[threadb,5,main]: Into Printb method ' s loop ...
Thread[threadb,5,main]: Into Printb method ' s loop ...
Thread[threadb,5,main]: Into Printb method ' s loop ...

As can be seen from the above results, Threada first calls the Run method and enters the PrintA method's for loop block, so the mutex is obtained first, and according to 2, THREADB cannot execute the PRINTB method. Add Join in Mainthread (10) in order to give Threada more time to allow it to enter the PrintA method first (this is because Threada need to complete a pirnt statement to obtain a mutex). If you remove the Join statement, you can verify the point.

Add a Printc method to the Printer class above:

1      Public void PRINTC () 2     {3         System.out.println (thread.currentthread () + ": Invoke Printc Method"); 4     }
View Code

Create a THREADC class:

1  Packagedemo;2 3  Public classThreadcextendsthread{4Printer p =NULL;5      PublicTHREADC (Printer p)6     {7          This. P =p;8     }9      Public voidRun ()Ten     { One          for(inti = 0; I < 5; i++) A         { - P.PRINTC (); -         } the     } -}
View Code

Then remove the join statement in the Mainthread, activate the thread THREADC, and run the result as follows (results may vary depending on the test):

Thread[thread-0,5,main]: Invoke Printc method
Thread[threada,5,main]: Invoke PrintA method
Thread[thread-0, 5,main]: Invoke Printc method
Thread[thread-0,5,main]: Invoke Printc method
Thread[threadb,5,main]: Invoke Printb method
Thread[threadb,5,main]: Into Printb method ' s loop ...
Thread[thread-0,5,main]: Invoke Printc method
Thread[thread-0,5,main]: Invoke Printc method
Thread[threadb , 5,main]: Into Printb method ' s loop ...
Thread[threadb,5,main]: Into Printb method ' s loop ...
Thread[threadb,5,main]: Into Printb method ' s loop ...
Thread[threadb,5,main]: Into Printb method ' s loop ...
Thread[threada,5,main]: Into PrintA method ' s loop ...
Thread[threada,5,main]: Into PrintA method ' s loop ...
Thread[threada,5,main]: Into PrintA method ' s loop ...
Thread[threada,5,main]: Into PrintA method ' s loop ...
Thread[threada,5,main]: Into PrintA method ' s loop ...

For the above results, you can combine the 2 to explain, for the remaining points in 2 and the case of the object, you can also test the validation itself. Verify 4 below.

The

Removes the static keyword from the PRINTB method declaration in the Printer method, replaces Printer.printb () with P.PRINTB () in the Threadb class Run method, and runs the result as follows:

Thread[threada,5,main]: Invoke PrintA method
Thread[threadb,5,main]: Invoke Printb method
Thread[threadb,5,main]: Into Printb method ' s loop ...
Thread[thread-0,5,main]: Invoke Printc method
Thread[threada,5,main]: Into PrintA method ' s loop ...
Thread[thread-0,5,main]: Invoke Printc method
Thread[thread-0,5,main]: Invoke Printc method
Thread[thread-0,5,main]: Invoke Printc method
Thread[thread-0,5,main]: Invoke Printc method
Thread[threadb,5,main]: Into Printb method ' s loop ...
Thread[threada,5,main]: Into PrintA method ' s loop ...
Thread[threadb,5,main]: Into Printb method ' s loop ...
Thread[threada,5,main]: Into PrintA method ' s loop ...
Thread[threadb,5,main]: Into Printb method ' s loop ...
Thread[threada,5,main]: Into PrintA method ' s loop ...
Thread[threadb,5,main]: Into Printb method ' s loop ...
Thread[threada,5,main]: Into PrintA method ' s loop ...

For the output, you crossing can analyze and analyze carefully.

(not to be continued ...) ;-))

This article is for reference: Devin Zhang's Blog

A brief exploration of Java synchronized keywords

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.