If a thread already exists in a synchronized method of the same object, other threads must wait until the thread ends before entering the method. So what happens if a class has multiple synchronized methods?
See the following code:
Public class test {<br/> static test T = new test (); <br/> static Test2 t2 = new Test2 (); </P> <p> Public static void main (string [] ARGs) {<br/> // todo auto-generated method stub </P> <p> testthread TT = T. new testthread (); <br/> TT. start (); <br/> try {<br/> thread. sleep (1000); <br/>} catch (interruptedexception e) {<br/> // todo auto-generated Catch Block <br/> E. printstacktrace (); <br/>}< br/> t2.test1 (); <br/>}</P> <p> class testthread extends thread {<br/> @ override <br/> Public void run () {<br/> // todo auto-generated method stub <br/> t2.test2 (); <br/>}</P> <p> class Test2 {<br/> Public synchronized void test1 () {<br/> system. out. println ("test1 called"); <br/>}</P> <p> Public synchronized void Test2 () {<br/> system. out. println ("Test2 called"); <br/> try {<br/> thread. sleep (3000); <br/>} catch (interruptedexception e) {<br/> // todo auto-generated Catch Block <br/> E. printstacktrace (); <br/>}< br/> system. out. println ("Test2 exit"); <br/>}< br/>}
The running result is as follows:
Test2 called <br/> Test2 exit <br/> test1 called
Obviously, when the Synchronized Method Test2 of the object T2 is called by the thread TT, the main thread cannot enter its test1 method until the call of the thread tt to the Test2 method ends, the main thread can enter the test1 method.
Conclusion: for the synchronized method, Java uses the object locking method. When any Synchronized Method is accessed, all other synchronized methods in the object cannot be accessed.
Next article: Java tip [010]: when the object A. Equals (B), A. hashcode = B. hashcode?