Java synchronization mechanism: Synchronized

Source: Internet
Author: User

Synchronized is a keyword of the Java language. When it is used to modify a method or a code block, it can ensure that at most one thread can execute the code segment at the same time. The synchronized keyword, which has two usage methods: Synchronized Method and synchronized block.

This article shows the use of the synchronized keyword in the form of code:

[1] Synchronized demo1:

Package COM. andyidea. demo;/*** when two concurrent threads access the synchronized (this) synchronization code block of the same object, * only one thread can be executed within a time period. The other thread must wait until the current thread executes the code block * Before executing the code block. * @ Author Andy. chen **/public class thread01 implements runnable {@ overridepublic void run () {synchronized (this) {for (INT I = 0; I <3; I ++) {system. out. println (thread. currentthread (). getname () + "synchronized loop" + I) ;}} public static void main (string [] ARGs) {thread01 t01 = new thread01 (); system. out. println ("Welcome to Andy. chen blog! \ N "+" synchronized keyword \ n "+" -------------------------- "); thread TA = new thread (t01," A "); thread TB = new thread (t01, "B"); TA. start (); TB. start ();}}

The running result is as follows:

Welcome to Andy. Chen blog! Synchronized keyword -------------------------- B synchronized loop 0b synchronized loop 1B synchronized loop 2a synchronized loop 0a synchronized loop 1A synchronized loop 2

[2] Synchronized demo2:

Package COM. andyidea. demo;/*** when a thread accesses a synchronized (this) synchronization code block of the object, * the other thread can still access the non-synchronized (this) synchronization code block of the object. * @ Author Andy. chen **/public class thread02 {public void method01 () {synchronized (this) {int I = 0; while (I ++ <3) {system. out. println (thread. currentthread (). getname () + ":" + I); try {thread. sleep (1000);} catch (interruptedexception e) {e. printstacktrace () ;}}} public void method02 () {// 1st Methods: When a thread accesses a synchronized (this) Synchronous Code block of an object, // another thread can still access the non-synchronized (this) Synchronous Code block in the object. // Int J = 0; // while (J ++ <3) {// system. out. println (thread. currentthread (). getname () + ":" + J); // try {// thread. sleep (1000); //} catch (interruptedexception e) {// E. printstacktrace (); //} // 2nd: When a thread accesses a synchronized (this) Synchronous Code block of an object, // access by other threads to all other synchronized (this) synchronization code blocks in the object will be blocked. Synchronized (this) {Int J = 0; while (J ++ <3) {system. out. println (thread. currentthread (). getname () + ":" + J); try {thread. sleep (1000);} catch (interruptedexception e) {e. printstacktrace () ;}}}/*** when a thread accesses a synchronized (this) synchronization code block of an object, * it obtains the object lock of this object. * As a result, access by other threads to all the synchronized code parts of the object is temporarily blocked. */Public synchronized void method3 () {int K = 0; while (K ++ <3) {system. out. println (thread. currentthread (). getname () + ":" + k); try {thread. sleep (1000);} catch (interruptedexception e) {e. printstacktrace () ;}} public static void main (string [] ARGs) {final thread02 t02 = new thread02 (); system. out. println ("Welcome to Andy. chen blog! \ N "+" synchronized keyword \ n "+" -------------------------- "); thread t02a = new thread (New runnable () {@ overridepublic void run () {t02.method01 () ;}, "A"); thread t02b = new thread (New runnable () {@ overridepublic void run () {t02.method02 ();}}, "B"); thread t02c = new thread (New runnable () {@ overridepublic void run () {t02.method3 () ;}, "C"); t02a. start (); t02b. start (); t02c. start ();}}

The running result is as follows:

Welcome to Andy. Chen blog! Use the synchronized keyword ------------------------ B: 1b: 2b: 3C: 1c: 2C: 3A: 1A: 2a: 3

[3] Synchronized demo3:

Package COM. andyidea. demo;/*** synchronized object lock * @ author Andy. chen **/public class thread03 {class innerobject {/*** internal class method 1 */private void innermethod01 () {int I = 0; while (I ++ <3) {system. out. println (thread. currentthread (). getname () + ":" + I); try {thread. sleep (1000);} catch (interruptedexception e) {e. printstacktrace () ;}}/ *** internal class method 2 */private void innermethod02 () {Int J = 0; while (J ++ <3) {system. out. P Rintln (thread. currentthread (). getname () + ":" + J); try {thread. sleep (1000);} catch (interruptedexception e) {e. printstacktrace () ;}}}/*** external class method 1 * @ Param innerobj */private void outermethod01 (innerobject innerobj) {synchronized (innerobj) {innerobj. innermethod01 () ;}}/*** external class method 2 * @ Param innerobj */private void outermethod02 (innerobject innerobj) {innerobj. innermethod02 ();} public static void main (Str Ing [] ARGs) {final thread03 t03 = new thread03 (); Final innerobject innerobj = t03.new innerobject (); system. Out. println ("Welcome to Andy. Chen blog! \ N "+" synchronized keyword \ n "+" -------------------------- "); thread t03a = new thread (New runnable () {@ overridepublic void run () {t03.outermethod01 (innerobj) ;}}, "A"); thread t03b = new thread (New runnable () {@ overridepublic void run () {t03.outermethod02 (innerobj );}}, "B"); t03a. start (); t03b. start ();}}

The running result is as follows:

Welcome to Andy. Chen blog! Use the synchronized keyword ------------------------ A: 1b: 1b: 2a: 2b: 3A: 3

Summary:

1. the synchronized method controls access to class member variables: each class instance corresponds to a lock, and each synchronized method must obtain the lock of the class instance that calls the method before execution, otherwise the thread is blocked, once the method is executed, the lock is exclusive until the lock is released when the method is returned. Then, the blocked thread can obtain the lock and re-enter the executable status. This mechanism ensures that, at the same time, only one of all the member functions declared as synchronized is in the executable state (because at most only one member function can obtain the lock corresponding to this type of instance ), this effectively avoids access conflicts between class member variables (as long as all methods that may be member variables of the category class are declared
Synchronized ).

2. the synchronized block is such a code block. The code must obtain the lock of the object syncobject (as mentioned earlier, it can be a class instance or class) before execution. It is highly flexible because it can target any code block and can specify any locked object.

Some Understanding of synchronized (this)
1. When two concurrent threads access the synchronized (this) synchronization code block of the same object, only one thread can be executed within a time period. The other thread must wait until the current thread finishes executing this code block before executing this code block.

2. However, when a thread accesses a synchronized (this) synchronization code block of the object, the other thread can still access the non-synchronized (this) synchronization code block of the object.

3. When a thread accesses a synchronized (this) synchronization code block of the object, other threads perform synchronization on all other synchronized (this) access to the synchronization code block will be blocked.

4. When a thread accesses a synchronized (this) synchronization code block of an object, it obtains the object lock of this object. As a result, access by other threads to all the synchronized code parts of the object is temporarily blocked.

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.