Keyword synchronized can be used as a Java method modifier or as a statement within the Java method. Code parts modified by its modes are often described as critical regions. This makes many people think that since the code is protected by Syscharonized, there is only one thread to access it at the same time.
For methods in the Java class, the keyword sysnchronized actually does not lock the method or some code of the method, which is just a lock object.
When Synchronized is made when making a method modifier, the Lock he has acquired will be handed over to the method caller (an object). If SYNCHRONIZED acts on a reference to an object, the obtained Lock will be given to the object referred to here. E.g:
Class test {public synchronized void method1 () // Note: Modification method {// .......}
Public void method2 () {synchronized (this) {// Note: References for modified objects // .....}}
Public void method3 (SomeObject Someobj) {synchronized (someobj) {// Note: References for modified objects // ...}}}
What is the synchronous control of an object? It illustrates that the thread that calls the method will acquire the object's LOCK. Holding the Lock thread of object A, if you apply for the Lock thread of the object A by the Synchronized function or the SYNCHRONIZED statement, it is not possible before the Lock is released. Therefore, the code within the Synchronized method or the SYNCHRONIZED section can have multiple threads at the same time, as long as the method is called for different objects. Such as the following code: Class Foo Extends Thread {Private Int Val; Public Foo (INT V) {VAL = V; PUBLIC SYNCHRONED VOID PrintVal (int V) {while (true) system.out.println (v);} public void Run () {PrintVal (VAL);}}
Class Bar Extends Thread {Private Foo Samefoo; Public Bar (Foo F) {Samefoo = f;
Public void Run () {Samefoo.printval (2);}} Class test {public static void main (string args []) {few f1 = new foo (1); f1.start (); bar b = new bar F1); B.Start (); foo f2 = new foo (3); f2.start ();}} Results: 1 1113333111333