1. When synchronized is used as a function modifier
Public synchronized void methodaaa ()
{< br> //....
}< br> It is equivalent to
Public void methodaaa ()
{< br> synchronized (this) // (1)
{< br> //.....
}< BR >}< br> it locks the object that calls the synchronization method.
2. Synchronization block, for exampleCodeAs follows:
Public void method3 (someobject so)
{
Synchronized (SO)
{
//.....
}
}
When a specific object is used as a lock, you can write it like this.ProgramBut when there is no clear object as the lock, just want to synchronize a piece of code, you can create a special instance variable (it must be an object) to act as the lock:
Class Foo implements runnable
{
Private byte [] Lock = new byte [0]; // special instance variable
Public void methoda ()
{
Synchronized (LOCK ){//... }
}
//.....
}
Note: creating a zero-Length byte array object is more economical than any other object-view the compiled bytecode: only three operation codes are required for generating a zero-Length byte [] object, object lock = new object () requires seven lines of operation code.
3. apply synchronized to the static function. The sample code is as follows:
Class foo
{
Public synchronized static void methodaaa () // synchronized static function
{
//....
}
Public void methodbbb ()
{
Synchronized (FOO. Class) // class literal (Class Name literal constant)
}
}
the methodbbb () method in the Code uses class literal as the lock. It produces the same effect as the synchronized static function, and the obtained lock is very special, is the class of the object currently calling this method (class, instead of a specific object generated by this class ).