Synchronous Synchronized Method and code block

Source: Internet
Author: User

For example, an object is like a big house, and the door is always open. There are many rooms in the house (that is, the method ). These rooms are locked (Synchronized Method) and cannot match
Locks (common method ). There is a key at the door of the room, which can open all the locked rooms. In addition, I compared all the threads that want to call this object method to enter a room in this house.
Person. There are so many things. Let's take a look at how these things work.

Here we will clarify our prerequisites. This object must have at least one Synchronized Method. Otherwise, what is the significance of this key. Of course there will be no such theme.

I
A person wants to enter a locked room. He comes to the door of the house and sees the key there (meaning no one else wants to use the locked room yet ). So he went up and got the key and made it according to his plan.
Use those rooms. Note that the key will be returned immediately after a locked room is used. Even if he wants to use two locked rooms in a row, he also needs to return the key in the middle and then get it back.

Therefore, in general, the key usage principle is: "pay-as-you-go, pay-as-you-go after use ."

At this time, other people can use unlocked rooms without restriction. One person can use one room, and two people can use one room without restriction. But if someone wants to enter the locked room, he will go to the gate to see it. If you have a key, you can only wait.

Yes
Many people are waiting for the key. After the key is returned, who will give priority to the key? Not
Guaranteed. Like the guy in the previous example who wants to use two locked rooms in a row, if another person is waiting for the key while returning the key, there is no guarantee that this guy can get it again.
(Java specifications are not guaranteed in many places, such as thread. how long will sleep () return to run after rest? The thread with the same priority will be executed first. When the lock of the object to be accessed is
After the release, multiple threads in the waiting pool will be given priority, and so on. I think the final decision lies in the JVM. The reason for this is that when JVM makes the above decision, it is not simply based on
A condition is used to make a judgment, but based on many items. Too many judgment conditions may affect Java promotion, or it may be because of intellectual property protection. Sun gave an warranty
And it's gone. It is understandable. But I believe that these uncertainties are not completely uncertain. Because the computer itself runs according to commands. Even if it looks very random, it is actually regular. Learned
Computers all know that the random numbers in computers are pseudo-random numbers. They are written in certain ways and look random. In addition, it may be because it is too time-consuming and meaningless to determine the cause.
If you are not sure, you are not sure .)

Let's take a look at the synchronization code block. It is slightly different from the synchronization method.

1. In terms of size, the synchronization code block is smaller than the synchronization method. You can regard the synchronization code block as a space separated by a locked screen in the unlocked room.

2. The synchronization code block can also be manually specified to obtain the key of another object. It is like specifying which key can be used to open the screen lock, you can use the key of the house; you can also specify the key of another house to open, in this case, you have to go to another house and bring the key, and use the key of the house to open the lock screen of the house.

Remember the key to the other house you got, and it does not affect other people entering the unlocked room of the house.

Is
What should I use a synchronous code block? I think it should be like this: first, the synchronization part of the program has a great impact on the running efficiency, and a method is usually to create some local variables first, and then perform some operations on these variables, such
Computing, display, and so on. The more Code covered by synchronization, the more serious the impact on efficiency. Therefore, we usually try to narrow down the impact scope. How to do it? Synchronous Code block. We only need to synchronize the data in one method.
Synchronization, such as operations.

In addition, the synchronization code block can specify the key. This feature has an additional benefit, that is, it can occupy the key of an object within a certain period of time. Do you still remember the principle of Key Usage in general cases. This is not a common situation. The key you obtained is not never returned, but is returned only when you exit the synchronization code block.

Also
Let's use the previous guy who wants to lock two rooms in a row. How can I continue to use the other one after I have used up one room. Use the synchronous code block. Create another thread, create a synchronous code block
Code block lock points to the house key. Start the thread. As long as you can catch the key of the house when you enter the code block, you can keep it until you exit the code block. That is to say, you can even
In order to traverse all locked rooms in the room, and even sleep (10*60*1000), there are still 1000 threads waiting for this key at the door of the room. Very enjoyable.

In
This section describes the relationship between the sleep () method and the key. When a thread fails to complete synchronization after obtaining the key, if it is forced to sleep (), the key remains there.
The key will not be returned until it runs again and completes all synchronization content. Remember, the guy just got tired of his work and went to bed. He didn't finish what he was going to do. To prevent others from entering the room
Even when he goes to bed, he will put the only key on his body.

Finally, some may ask, why do we need a key instead of a key? I think this is purely a matter of complexity. One key and one door are safer, but there are many problems involved. Key generation, storage, acquisition, and return. Its complexity may increase with the increase of Synchronization Methods in Geometric Order, seriously affecting efficiency.

This is a trade-off. To increase security, the efficiency is greatly reduced.

From: http://www.54bk.com/more.asp? Name = CZP & id = 2097

1. When two concurrent threads access the synchronized (this) synchronization code block of the same object, only one thread can be executed within a time period. The other thread must wait until the current thread finishes executing this code block before executing this code block.

2. However, when a thread accesses a synchronized (this) synchronization code block of the object, the other thread can still access the non-synchronized (this) synchronization code block of the object.

3. When a thread accesses a synchronized (this) synchronization code block of the object, other threads perform synchronization on all other synchronized (this) access to the synchronization code block will be blocked.

4. The third example also applies to other synchronous code blocks. That is to say, when a thread accesses a synchronized (this) synchronization code block of an object, it obtains the object lock of this object. As a result, access by other threads to all the synchronized code parts of the object is temporarily blocked.

5. The above rules apply to other Object locks.

Example:

1. When two concurrent threads access the synchronized (this) synchronization code block of the same object, only one thread can be executed within a time period. The other thread must wait until the current thread finishes executing this code block before executing this code block.

Package ths;

Public class thread1 implements runnable {
Public void run (){
Synchronized (this ){
For (INT I = 0; I <5; I ++ ){
System. Out. println (thread. currentthread (). getname () + "synchronized loop" + I );
}
}
}
Public static void main (string [] ARGs ){
Thread1 T1 = new thread1 ();
Thread TA = new thread (T1, "");
Thread TB = new thread (T1, "B ");
Ta. Start ();
TB. Start ();
}
}

Result:

A Synchronized loop 0
A Synchronized loop 1
A Synchronized loop 2
A Synchronized loop 3
A Synchronized loop 4
B synchronized loop 0
B synchronized loop 1
B synchronized loop 2
B synchronized loop 3
B synchronized loop 4

2. However, when a thread accesses a synchronized (this) synchronization code block of the object, the other thread can still access the non-synchronized (this) synchronization code block of the object.

Package ths;

Public class thread2 {
Public void m4t1 (){
Synchronized (this ){
Int I = 5;
While (I --> 0 ){
System. Out. println (thread. currentthread (). getname () + ":" + I );
Try {
Thread. Sleep (500 );
} Catch (interruptedexception IE ){
}
}
}
}
Public void m4t2 (){
Int I = 5;
While (I --> 0 ){
System. Out. println (thread. currentthread (). getname () + ":" + I );
Try {
Thread. Sleep (500 );
} Catch (interruptedexception IE ){
}
}
}
Public static void main (string [] ARGs ){
Final thread2 myt2 = new thread2 ();
Thread T1 = new thread (
New runnable (){
Public void run (){
Myt2.m4t1 ();
}
}, "T1"
);
Thread t2 = new thread (
New runnable (){
Public void run (){
Myt2.m4t2 ();
}
}, "T2"
);
T1.start ();
T2.start ();
}
}

Result:

T1: 4
T2: 4
T1: 3
T2: 3
T1: 2
T2: 2
T1: 1
T2: 1
T1: 0
T2: 0

3. When a thread accesses a synchronized (this) synchronization code block of the object, other threads perform synchronization on all other synchronized (this) access to the synchronization code block will be blocked.

// Modify the thread2.m4t2 () method:

Public void m4t2 (){
Synchronized (this ){
Int I = 5;
While (I --> 0 ){
System. Out. println (thread. currentthread (). getname () + ":" + I );
Try {
Thread. Sleep (500 );
} Catch (interruptedexception IE ){
}
}
}

}

Result:

T1: 4
T1: 3
T1: 2
T1: 1
T1: 0
T2: 4
T2: 3
T2: 2
T2: 1
T2: 0

4. The third example also applies to other synchronous code blocks. That is to say, when a thread accesses a synchronized (this) synchronization code block of an object, it obtains the object lock of this object. As a result, access by other threads to all the synchronized code parts of the object is temporarily blocked.

// Modify thread2.m4t2 () as follows:

Public synchronized void m4t2 (){
Int I = 5;
While (I --> 0 ){
System. Out. println (thread. currentthread (). getname () + ":" + I );
Try {
Thread. Sleep (500 );
} Catch (interruptedexception IE ){
}
}
}

Result:

T1: 4
T1: 3
T1: 2
T1: 1
T1: 0
T2: 4
T2: 3
T2: 2
T2: 1
T2: 0

5. The above rules apply to other Object locks:

Package ths;

Public class thread3 {
Class inner {
Private void m4t1 (){
Int I = 5;
While (I --> 0 ){
System. Out. println (thread. currentthread (). getname () + ": inner. m4t1 () =" + I );
Try {
Thread. Sleep (500 );
} Catch (interruptedexception IE ){
}
}
}
Private void m4t2 (){
Int I = 5;
While (I --> 0 ){
System. Out. println (thread. currentthread (). getname () + ": inner. m4t2 () =" + I );
Try {
Thread. Sleep (500 );
} Catch (interruptedexception IE ){
}
}
}
}
Private void m4t1 (inner ){
Synchronized (inner) {// use the object lock
Inner. m4t1 ();
}
}
Private void m4t2 (inner ){
Inner. m4t2 ();
}
Public static void main (string [] ARGs ){
Final thread3 myt3 = new thread3 ();
Final inner = myt3.new inner ();
Thread T1 = new thread (
New runnable (){
Public void run (){
Myt3.m4t1 (inner );
}
}, "T1"
);
Thread t2 = new thread (
New runnable (){
Public void run (){
Myt3.m4t2 (inner );
}
}, "T2"
);
T1.start ();
T2.start ();
}
}

Result:

Although thread T1 acquires the object lock on the inner, thread T2 accesses the non-synchronous part of the same inner. Therefore, the two threads do not interfere with each other.

T1: inner. m4t1 () = 4
T2: inner. m4t2 () = 4
T1: inner. m4t1 () = 3
T2: inner. m4t2 () = 3
T1: inner. m4t1 () = 2
T2: inner. m4t2 () = 2
T1: inner. m4t1 () = 1
T2: inner. m4t2 () = 1
T1: inner. m4t1 () = 0
T2: inner. m4t2 () = 0

Now add synchronized before inner. m4t2:

Private synchronized void m4t2 (){
Int I = 5;
While (I --> 0 ){
System. Out. println (thread. currentthread (). getname () + ": inner. m4t2 () =" + I );
Try {
Thread. Sleep (500 );
} Catch (interruptedexception IE ){
}
}
}

Result:

Although thread t1 and t2 access two unrelated parts of the same inner object, because T1 first obtains the object lock on inner, so T2 has access to inner. access to m4t2 () is also blocked because m4t2 () is a synchronous method in the inner.

T1: inner. m4t1 () = 4
T1: inner. m4t1 () = 3
T1: inner. m4t1 () = 2
T1: inner. m4t1 () = 1
T1: inner. m4t1 () = 0
T2: inner. m4t2 () = 4
T2: inner. m4t2 () = 3
T2: inner. m4t2 () = 2
T2: inner. m4t2 () = 1
T2: inner. m4t2 () = 0

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.