Public classMyService {PrivateString lock = "123"; Public voidTestMethod () {synchronized(lock) {System.out.println (Threadb.currentthread (). GetName ()+ "Begin" +System.currenttimemillis ()); Lock= "456"; Try{threadb.sleep (2000); System.out.println (Threadb.currentthread (). GetName ()+ "End" +System.currenttimemillis ()); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } } }
Lock lock changed from "123" to "456"
Threada and THREADB
Public classThreadaextendsThread {PrivateMyService MyService; PublicThreada (MyService myservice) { This. MyService =MyService; } Public voidrun () {Myservice.testmethod (); }} Public classThreadbextendsThread {PrivateMyService MyService; Publicthreadb (MyService myservice) { This. MyService =MyService; } Public voidrun () {Myservice.testmethod (); }}
View Code
Run
Public class Run { publicstaticvoidthrows interruptedexception { New myservice (); Threada Threadanew Threada (myservice); Threada.start (); Thread.Sleep (+); Threada threadbnew Threada (myservice); Threadb.start (); } }
If Thread.Sleep (50) is commented out, the locks acquired by A and B are "123", although the lock is changed to "456", the result is still synchronous.
Java Multithreading (ii) Change of Synchronized lock object