The first conclusion:
class method, synchronized locks the object this, only methods that call the same object need to acquire the lock. At the same time, all synchronize methods in the same object can call only one
In a static method, synchronized locks the entire class object, similar to (X.class), in which all static methods with synchronized are called, one at a time only
1 classSync {2 3 Public synchronized voidTest () {4System.out.println ("Test start:");5 Try {6Thread.Sleep (1000);7}Catch(interruptedexception e) {8 e.printstacktrace ();9 }TenSYSTEM.OUT.PRINTLN ("Test End:"); One } A - Public synchronized voidtest2 () { -System.out.println ("test2 start ..."); the Try { -Thread.Sleep (800); -}Catch(interruptedexception e) { - e.printstacktrace (); + } -System.out.println ("Test2 End:"); + } A } at - classMyThreadextendsThread { - - Privatesync sync; - - PublicMyThread (Sync sync) { in This. sync =sync; - } to + Public voidrun () { - sync.test (); the } * } $ Panax Notoginseng classMyThread2extendsThread { - the Privatesync sync; + A PublicMyThread2 (Sync sync) { the This. sync =sync; + } - $ Public voidrun () { $ sync.test2 (); - } - } the - Public classMain {Wuyi the Public Static voidMain (string[] args) { -Sync sync =NewSync (); WuThread thread =NewMyThread (sync); -Thread thread2 =NewMyThread2 (sync); About Thread.Start (); $ Thread2.start (); - - } -}
Operation Result:
Test start:
Test end:
Test2 begins.
Test2 End:
The scenario is executed sequentially, indicating that the same object is locked:
The main method is replaced by the following notation:
1 Public Static void Main (string[] args) {2 New MyThread (new Sync ()); 3 New MyThread2 (new Sync ()); 4 Thread.Start (); 5 Thread2.start (); 6 7 }
Results:
Test start:
Test2 begins.
Test2 End:
Test end:
Synchronized does not play a synchronous role, stating that it is not the same lock
static method:
1 classSync {2 3 Public Static synchronized voidTest () {4System.out.println ("Test start:");5 Try {6Thread.Sleep (1000);7}Catch(interruptedexception e) {8 e.printstacktrace ();9 }TenSYSTEM.OUT.PRINTLN ("Test End:"); One } A - Public Static synchronized voidtest2 () { -System.out.println ("test2 start ..."); the Try { -Thread.Sleep (800); -}Catch(interruptedexception e) { - e.printstacktrace (); + } -System.out.println ("Test2 End:"); + } A } at - classMyThreadextendsThread { - - Public voidrun () { - sync.test (); - } in } - to classMyThread2extendsThread { + - Public voidrun () { the sync.test2 (); * } $ }Panax Notoginseng - Public classMain { the + Public Static voidMain (string[] args) { AThread thread =NewMyThread (); theThread thread2 =NewMyThread2 (); + Thread.Start (); - Thread2.start (); $ $ } -}
Operation Result:
Test start:
Test end:
Test2 begins.
Test2 End:
This article refers to the blog of Forks: Java thread synchronization: synchronized locks the code or the object
Does the Java synchronized lock the entire object or only the method