One, the synchronization method is synchronized keyword-modified methods . Because each object in Java has a built-in lock, the built-in lock protects the entire method when the method is decorated with this keyword. You need to get the built-in lock before calling the method, otherwise it will be in a blocking state.Note: The Synchronized keyword can also modify a static method, at which point the entire class is locked if the static method is called.
second, synchronous code blockThat is, a statement block that has the synchronized keyword modifier. The block of statements modified by the Synchronized keyword is automatically added with a built-in lock, which enables synchronization of code such as:
Synchronized (object) {}
Note: Synchronization is a high-overhead operation, so you should minimize the content of synchronization. It is usually not necessary to synchronize the entire method, using the synchronized code block to synchronize the key code.
A thread is exclusive when it executes a synchronous method. when any thread enters any of the synchronization methods of an object, all the synchronization methods of the object are locked, during which time no other thread can access any of the synchronization methods of the object until the thread executes the synchronous method it calls and exits from it. This causes it to release the object after the synchronization lock. after an object is locked by a thread, the other threads are all non-synchronous methods that can access the object.
Synchronization Block: The synchronization block synchronizes the code contained in the synchronization block by locking a specified object, while the synchronization method synchronizes the code in the method block, and in this case the locked object is the principal object itself that the synchronization method belongs to. What if this method is a static synchronization method? The thread locking is not the object of this class, nor the class itself, but the object of the Java.lang.Class type corresponding to this class. The interaction between the synchronization method and the synchronization block is limited to the same object, so the static synchronization method is restricted only by other static synchronization methods of the class to which it belongs, but not with instances (objects) of the class.
If an object has both a synchronous method and a synchronization block, then when either of the synchronization methods or the synchronization block is executed by a thread, the object is locked, the other thread cannot access the object's synchronization method at this time, and the synchronization block cannot be executed.
The synchronized keyword is used to protect shared data . Please note that "shared data", you must distinguish which data is shared data, see the following example:
The purpose of synchronized is to make multiple threads of the same object, and at some point only one of the threads can access the object's synchronized data. Each object has a "lock flag", and when a thread of this object accesses one of the object's synchronized data, all the synchronized-modified data for that object is locked (because the "lock flag" is taken away by the current thread), The current thread frees the "lock flag" only if the front-end accesses the synchronized data it wants to access, so that other threads of the same object have access to the synchronized data.
third, wait and notify
Wait (): causes a thread to be in a wait state and releases the lock of the object it holds.
Sleep (): Makes a running thread sleep, is a static method that calls this method to catch the interruptedexception exception.
Notify (): Wakes up a waiting thread, noting that when this method is called, it does not actually wake up a waiting state thread, but is determined by the JVM to wake up which thread, and not by priority.
Notityall (): Wakes all the threads that are in the waiting state, noting that they do not give all the wake-up threads an object lock, but instead let them compete.
Iv. using special domain variables (volatile) to implement thread synchronization The A.volatile keyword provides a lock-free mechanism for access to domain variables B. Using a volatile modifier domain is equivalent to telling a virtual machine that the domain might be updated by another thread. Therefore, each use of the domain is recalculated instead of making Using the value D.volatile in the register does not provide any atomic operation, nor can it be used to decorate the final type of variable five, using a re-entry lock to implement thread synchronization a new Java.util.concurrent package is added in JavaSE5.0 to support synchronization. The Reentrantlock class is a re-entrant, mutex, and lock interface that implements the same basic behavior and semantics as using synchronized methods and blocks, and extends its capabilities. Common methods of the Reenreantlock class are:
Note: Reentrantlock () also has a construction method that can create a fair lock, but is not recommended because it can significantly reduce the efficiency of program operation
Private lock lock = new Reentrantlock (); Lock.lock ();
Shared resources
Lock.unlock ();
Note: About the lock object and synchronized keyword selection:A. It is best to use a mechanism provided by the Java.util.concurrent package to help users handle all lock-related code. B. If the synchronized keyword satisfies the user's needs, use synchronized because it simplifies the code C. If you need more advanced features, use the Reentrantlock class, you should pay attention to release the lock in time, otherwise there will be deadlock, usually in the finally code release lock VI, using local variables to implement thread synchronization if you use Threadlocal management variables, Each thread that uses the variable obtains a copy of the variable, and the replicas are independent of each other so that each thread can modify its own copy of the variable without affecting other threads. Common methods of ThreadLocal class
ThreadLocal (): Creates a thread local variable get (): Returns the value in the current thread copy of this thread's local variable InitialValue (): Returns the "initial value" set (T value) of the current thread for this thread's local variable: the current thread vice of this thread local variable The value in this is set to value
public class bank{//Use ThreadLocal class to manage shared variables account private static threadlocal<integer> account = new Threadlocal<integer> () { @Override protected Integer initialvalue () { return; } };
public void Save (int money) { account.set (Account.get () +money); }
public int Getaccount () { return account.get (); }
}
Note: Threadlocal and synchronization mechanisms are both a.threadlocal and synchronous mechanisms to solve the problem of access violation of the same variable in multi-threading. B. The former adopts a "space-for-time" approach, which uses "time-for-space" approachesVii. using a blocking queue for thread synchronization
The previous 5 synchronization methods are synchronous at the bottom of the thread, but we should try to stay away from the underlying structure as far as possible in actual development. Using the new Java.util.concurrent package in the javaSE5.0 release will help simplify development. This section mainly uses linkedblockingqueue<e> to implement thread synchronization linkedblockingqueue<e> is an arbitrary blocking queue based on the connected node. Queues are first in, out of sequence (FIFO), about the queue will be explained in detail ~linkedblockingqueue class common Methods Linkedblockingqueue (): Create a capacity of integer.max_ The value of Linkedblockingqueue put (e): Adds an element at the end of the queue and blocks the size (): Returns the number of elements in the queue take (): Remove and return the team header element, or block code instances if the queue is empty: implementing Merchant products and traders Synchronization of Products
Note:blockingqueue<e> defines the common methods of blocking queues, especially three ways to add elements, and we should pay more attention when the queue is full:
The Add () method throws an exception
Offer () method returns false
The put () method blocks
7. Using atomic variables for thread synchronization
The root cause of the need to use thread synchronization is that operations on ordinary variables are not atomic.
So what is atomic manipulation? Atomic manipulation means reading the value of a variable, modifying the value of a variable, saving the value of a variable as a whole--these behaviors are either completed at the same time or are not completed. A tool class that creates an atomic type variable is provided in the Java util.concurrent.atomic package to simplify thread synchronization. Where the atomicinteger table can atomically update the value of int, available in an application (such as an atom-incremented counter), but cannot be used to replace an integer; Allows for unified access to tools and utilities that deal with the opportunity number class.
Common methods of the Atomicinteger class:
Atomicinteger (int initialvalue): Creates a new with the given initial value
Atomicintegeraddaddget (int dalta): atomically adds the given value to the current value
Get (): Gets the current value
Java Multithreaded synchronization method