Java tip []: Synchronized Locking method in multiple threads

Source: Internet
Author: User

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?

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.