Synchronous implementation of Java

Source: Internet
Author: User

In Java programming, it is often necessary to use synchronization, and the most common implementation of synchronization is the Synchronized keyword.

Synchronized keyword refers to the concept of "lock", first of all to understand the relevant lock knowledge.

Built-in lock for Java: Each Java object can be used as a lock that implements synchronization, and these locks become built-in locks. When a thread enters a synchronous code block or method, the lock is automatically acquired, and the lock is freed when the synchronization code block or method exits. The only way to get a built-in lock is to enter this lock's protected synchronous code block or method.

The Java built-in lock is a mutex, which means that at most one thread can get the lock, and when thread a tries to get the built-in lock held by thread B, thread A must wait or block until thread B releases the lock, and a thread will wait forever if the B thread does not release the lock.

Lock by level in Java can be divided into: Object lock or method lock, class lock two kinds.

Java's object locks (or method locks) and class locks are basically consistent with the built-in locks in terms of locks, but there is a big difference between object locks and class locks.

Difference: 1. Object lock is used for object instance methods, and class locks are used for static methods of classes or for class objects of classes.

2. Classes can have multiple objects, so different object instances can have multiple object locks and do not interfere with each other. Each class has only one class object, so each class has only one lock.

Synchronized usage: Synchronized Modify the method or synchronized the code block.

The following is a concrete example of how the two usages differ in object locks and class locks:

Synchronized decoration methods and code blocks for object locks:

 Public classTestsynchronizedforobjectlock { Public voidtest1 () {synchronized( This){            intI=5;  while(i--> 0) {System.out.println (Thread.CurrentThread (). GetName ()+ ":" +i); Try{Thread.Sleep (500); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }        }    }         Public synchronized voidtest2 () {intI =5;  while(i--> 0) {System.out.println (Thread.CurrentThread (). GetName ()+ ":" +i); Try{Thread.Sleep (500); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }    }     Public Static voidMain (string[] args) {Testsynchronizedforobjectlock T=NewTestsynchronizedforobjectlock (); Thread T1=NewThread (NewRunnable () { Public voidRun () {t.test1 ();}}, "Test1"); Thread T2=NewThread (NewRunnable () { Public voidRun () {t.test2 ();}}, "Test2");        T1.start ();    T2.start (); }}

The result of its operation:

 test1:4test1:  3test1:  2test1:  1test1:  0TEST2:  4test2:  3test2:  2test2:  1test2:  0 

The code above, the first method is synchronized with a synchronous block of code, the incoming object instance is this, indicates the current object, and the second method is synchronized in a way that modifies the method. Because the first synchronization code block passed in this, so the two synchronous code to obtain the object lock is the same object lock, the following main method opens two threads respectively, calls the Test1 and Test2 methods respectively, then two threads need to obtain the object lock, the other thread must wait. The above also gives the result of the operation can be seen: until the test1 thread executes, release the lock, the TEST2 thread will start executing.

If we get rid of the synchronized keyword of the Test2 method, what will it do? Run Result:

 test1:4test2:  4test2:  3test1:  3test2:  2test1:  2test2:  1test1:  1test2:  0test1:  0 

above is the result of execution, and we can see that the output of the result is alternately output, because one thread gets the object lock, but another thread can access the method or code that is not synchronized. The method of synchronization (locking method) and the method without synchronization (normal method) are not affected, one thread enters the synchronization method, the object lock is obtained, and other threads can access the methods that are not synchronized (common method).

So synchronized is just a locking mechanism for a built-in lock, and when a method is added to the Synchronized keyword, it means that the built-in lock can be executed, Does not prevent other threads from accessing methods that do not need to obtain the built-in lock.

Synchronized decoration methods and code blocks for class locks:

 Public classTestsynchronizedforclasslock { Public voidtest3 () {synchronized( This. GetClass ()) {            intI=5;  while(i--> 0) {System.out.println (Thread.CurrentThread (). GetName ()+ ":" +i); Try{Thread.Sleep (500); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }        }    }         Public Static synchronized voidtest4 () {intI=5;  while(i--> 0) {System.out.println (Thread.CurrentThread (). GetName ()+ ":" +i); Try{Thread.Sleep (500); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }    }     Public Static voidMain (string[] args) {Testsynchronizedforclasslock C=NewTestsynchronizedforclasslock (); Thread T3=NewThread (NewRunnable () { Public voidrun () {c.test3 ();}}); Thread T4=NewThread (NewRunnable () { Public voidrun () {testsynchronizedforclasslock.test4 ();}});        T3.start ();    T4.start (); }}

Operation Result:

 thread-0:4thread  -0:3thread  -0:2< Span style= "COLOR: #000000" >thread  -0:1thread  -0:0 thread  -1:4thread  -1:3 thread  -1:2thread  -1:1 thread  -1:0 

In fact, the effect of the class lock modification method and the code block is the same as the object lock, because the class lock is only an abstraction concept, just to distinguish the characteristics of the static method, because the static method is common to all object instances, so the static method corresponding to the synchronized modified lock is also unique, So abstract out a class lock. In fact, the focus here is the following code, synchronized both static and non-static methods :

 Public classTestsynchronizedforclasslock { Public synchronized voidtest3 () {intI=5;  while(i--> 0) {System.out.println (Thread.CurrentThread (). GetName ()+ ":" +i); Try{Thread.Sleep (500); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }            }         Public Static synchronized voidtest4 () {intI=5;  while(i--> 0) {System.out.println (Thread.CurrentThread (). GetName ()+ ":" +i); Try{Thread.Sleep (500); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }    }     Public Static voidMain (string[] args) {Testsynchronizedforclasslock C=NewTestsynchronizedforclasslock (); Thread T3=NewThread (NewRunnable () { Public voidrun () {c.test3 ();}}); Thread T4=NewThread (NewRunnable () { Public voidrun () {testsynchronizedforclasslock.test4 ();}});        T3.start ();    T4.start (); }}

Operation Result:

 thread-0:4thread  -1:4thread  -0:3< Span style= "COLOR: #000000" >thread  -1:3thread  -0:2 thread  -1:2thread  -0:1 thread  -1:1thread  -1:0 thread  -0:0 

The above code synchronized both static and instance methods, but the result of the operation is alternating, which proves that the class lock and object lock are two different locks, which control various areas, and they are not interfering with each other. Similarly, when a thread obtains an object lock, it can also get the lock, which is allowed by acquiring two locks at the same time.

Synchronous implementation of 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.