The analysis of the possible misunderstanding of the line Cheng synchronized

Source: Internet
Author: User

After using synchronized, it is not said that the synchronized lock method or block of code can be executed one time before jumping to another thread. Instead, when two concurrent threads access the same object in the synchronized (this) synchronization code block, only one thread can be executed within a single time. The other thread must wait for the current thread to finish executing the block before it can execute the code block. That is, even if a method is locked, the thread can still jump if other threads are not accessing the method. Here's an example:

1  Public classtest2{2      Public Static voidMain (string[] args) {3Thread a=NewA2 ();4Thread b=NewB2 ();5 A.start ();6 B.start ();7     }8 }9 Ten classA2extendsthread{ One      Public voidrun () { A Show1 (); -     } -      Public synchronized voidShow1 () { the          for(inti=0;i<20;i++){ - System.out.print (i); -         } -     }         + } -  + classB2extendsthread{ A      Public voidrun () { at Show2 (); -     } -      Public synchronized voidShow2 () { -          for(inti = 0; I < 20; i++) { - System.out.print (i); -         } in     } -}

Two threads were created, each accessing their own locking show method, the final result is not necessarily two consecutive 1-19, I run the result is as follows:

001122334455667788991010111112121313141415161718191516171819

So synchronized is only valid for different threads that access the same method.

The analysis of the possible misunderstanding of the line Cheng synchronized

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.