1. Synchronized principle
In Java, each object has and has only one synchronization lock. This also means that the synchronization lock is dependent on the object and exists.
When we call the Synchronized method of an object, we get a synchronized lock on the object. For example, synchronized (obj) acquires a synchronized lock on the "obj" object.
The access of different threads to the synchronization lock is mutually exclusive. In other words, a point in time, the object's synchronization lock can only be obtained by a thread! By synchronizing the locks, we can implement mutually exclusive access to the object/method in multiple threads. For example, there are now two threads A and thread B that will access the synchronization lock for object obj. Suppose, at some point, thread a gets to "obj's Sync lock" and performs some action; at this point, thread B also attempts to get "obj's Sync lock"--thread B gets failed, and it must wait until thread a releases "Sync lock for this object" before thread B gets the "Sync Lock for obj" So that they can run.
2. Synchronized Basic Rules
We summarize the basic rules of synchronized into the following 3 articles and illustrate them through an example.
First: When a thread accesses the synchronized method or synchronized code block of an object, access to that object's synchronized method or synchronized code block is blocked by other threads.
Second: When a thread accesses the "synchronized method" or "Synchronized code block" of "an object", other threads can still access the asynchronous code block of "that object".
Article three: When a thread accesses the "synchronized method" or "Synchronized code block" of "an object", other threads will block access to other "synchronized methods" or "synchronized code blocks" of the object.
First article
When a thread accesses the synchronized method or synchronized code block of an object, access to that object's synchronized method or synchronized code block is blocked by other threads.
The following is the demo program for "Synchronized code block".
Class Myrunable implements Runnable {
@Override public
void Run () {
synchronized (this) {
try {
int i = 0; I < 5; i++) {
thread.sleep (100);//Hibernate 100ms
System.out.println (Thread.CurrentThread (). GetName () + "loop" + i);
}
' catch (Interruptedexception IE) {}}} ' public
class Demo1_1 {public
static void Main (string[] args) {
Runnable demo = new Myrunable (); New "Runnable object"
thread t1 = new Thread (demo, "T1"); New "Thread T1", T1 is based on demo this runnable object
thread t2 = new Thread (demo, "T2"); New "Thread T2", T2 is based on demo this runnable object
t1.start (); Start "Thread T1"
t2.start (); Start the thread T2
}
}
Run Result:
T1 Loop 0
T1 loop 1
t1 loop 2
t1 loop 3
t1 loop 4
T2 loop 0
T2 loop 1
T2 loop 2
T2 Loop 3< C9/>t2 Loop 4