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 not locked (normal method ). There is a key at the door of the room, which can open all the locked rooms. In addition, I compared all threads that want to call this object method to those who want to enter a room in this house. 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.
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 used the room as planned. 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.
If many people are waiting for the key, who will get the key first after the key is returned? 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 the sleep () run be returned after the rest? The thread with the same priority is first executed. When the lock to access the object is released, multiple threads in the waiting pool will get the first 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 does not simply make a judgment based on one condition, but based on many items. Too many judgment conditions may affect Java promotion, or it may be because of intellectual property protection. Sun gave me an uncertain message, and it would have been mixed up. 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. All those who have learned about computers Know that the names of random numbers in computers are pseudo-random numbers. They are written in certain ways and seem to be random. In addition, it may be because it is too time-consuming and meaningless to be sure, so you are not sure if 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.
Why 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 as computing and display. 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 synchronize the synchronization location in a method, such as an operation.
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.
We also used the guy who wanted to lock two rooms in a row as an example. 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, and point the lock of the code block to the key of the house. 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 traverse all locked rooms in the room, or even sleep (10*60*1000), while there are still 1000 threads waiting for this key at the door of the room. Very enjoyable.
Let's talk about the correlation 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. In order to prevent others from entering the room and making a mess inside, even when he is sleeping, he should 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.