1. Prerequisites for synchronization
Multiple threads
Multiple threads are using the same lock
2. Benefits of synchronization
The advent of synchronization solves the security problem of multithreading
3. Disadvantages of synchronization
When the thread is more, because each thread will judge the lock on the synchronization, this is very resource-intensive, it will reduce the efficiency of the program running.
4. Synchronization method:
1. Is the synchronization of the keyword, synchronized added to the method, the lock object is this
2. The lock object of the static method is the bytecode file object of the class, Xxx.class
Lock locks after 5.jdk5
Two methods of the lock interface
Lock (): Get lock
Unlock (): Release lock
Sub-class: Reentrantlock ()
By calling these two methods of the subclass, acquiring the lock, releasing the lock, and wrapping the code block that needs to be synchronized, you can also solve the thread safety problem. The following pseudocode:
Reentrantlock lock= new Reentrantlock ();
try{
Lock.lock ();
Synchronization code;
}finally{
Lock.unlock ();
}
6. Synchronization drawbacks
A. Low efficiency
B. If there is a synchronous nesting, it is easy to create a deadlock
Deadlock: Two or more threads, which are waiting for each other in the process of competing for resources.
7. Inter-thread communication
Different kinds of threads operate on the same resource. (Producer, consumer)
Producers, consumers, waiting for the wake-up mechanism:
Java Multithreading (four)