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 <