Java multithreading guide for beginners (11): Use the Synchronized block Synchronization Method

Source: Internet
Author: User

SynchronizedThe keyword can be used in two ways. FirstHtml ">Synchronous class method using the Synchronized keywordThe description in this article is directly used in the definition of methods. The other isSynchronizedBlock. We can not onlySynchronizedBlock to an object variable in the same step. You can also useSynchronizedBlock to synchronize static and non-static methods in the class.

SynchronizedThe block syntax is as follows:

Public   Void Method ()
{
... ...
Synchronized (Expression)
{
... ...
}
}

1. Non-static method Synchronization

SlaveSynchronous class method using the Synchronized keywordArticle MediumWe know thatSynchronizedIf you use a keyword to define a method, all the usage of the class will be locked.SynchronziedStatic or non-static methods defined by the keyword, but this is not easy to understand. If you useSynchronizedBlock to achieve the same effect, it is not difficult to understand why this effect occurs. If you want to useSynchronizedBlock to lock all non-static synchronous methods in the class, you need to useThisAsSynchronizedBlock parameter inputSynchronizedThe Code is as follows:

PassSynchronizedBlock synchronization non-static method

001 Public   Class SyncBlock
002 {
003 Public   Void Method1 ()
004 {
005 Synchronized ( This ) // Equivalent to using the synchronized keyword for the method1 Method
006 {
007 ... ...
008 }
009 }
010 Public   Void Method2 ()
011 {
012 Synchronized ( This ) // Equivalent to using the synchronized keyword for the method2 Method
013 {
014 ... ...
015 }
016 }
017 <

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.