Why use Sync?
Java allows multithreading concurrency control, when multiple threads simultaneously manipulate a shareable resource variable (such as data additions and deletions), will result in inaccurate data and conflict with each other. Therefore, a sync lock is added to avoid being called by other threads to, to ensure that the variable is unique and accurate until the thread has completed the operation. 1. Synchronization methods The method that has the Synchronized keyword modifier. Because every object in Java has a built-in lock,, built-in locks protect the entire method when the method is modified with this keyword. You need to get the built-in lock before calling the method, otherwise it will be in a blocking state. 2. Synchronous code block a statement block with synchronized keyword adornments. The statement block modified by this keyword is automatically added with built-in locks for synchronization 3. Thread synchronization with special domain variables (volatile) 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, C. Therefore, each time the domain is used, it is recalculated instead of using the value in the Register D.volatile does not provide any atomic operation, nor can it be used to modify the final type of variable Note: The non-synchronous problem in multi-threading is mainly in the reading and writing of the domain, and if the domain itself avoids this problem, it is not necessary to modify the method of manipulating the domain. With the final domain, locked-protected and volatile domains can avoid unsynchronized problems. 4. Thread synchronization using a re-enter lock A new java.util.concurrent package is added to JavaSE5.0 to support synchronization. The Reentrantlock class is a reentrant, mutually exclusive, lock that implements the locking interface, It has the same base as using the Synchronized method and fastThis behavior and semantics, and expands its capabilities 5. Thread synchronization with local variables If you use threadlocal to manage variables, each thread that uses the variable gets a copy of the variable, Replicas are independent of each other so that each thread is free to modify its own copy of the variable without affecting other threads.
About thread synchronization