java allows multi-threaded concurrency control, when multiple threads concurrently manipulate a shareable resource variable (such as data additions and deletions), will result in inaccurate data and conflict with each other, so join the sync lock to avoid before the thread does not complete the operation , called by other threads, to ensure the uniqueness and accuracy of the variable. 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. code such as: public synchronized void Save () {} NOTE: The Synchronized keyword can also modify a static method, at which point the entire class 2 will be locked if the static method is called. Synchronizing code blocks A statement block that has synchronized keyword adornments. The statement block modified by this keyword is automatically added with a built-in lock for synchronization code such as: synchronized (object ) { } Note: Synchronization is a high-overhead operation, so you should minimize the content of synchronization. There is usually no need to synchronize the entire method, using the synchronized code block to synchronize the key code. code example: copy code package com.xhj.thread; & nbsp /** * Use of thread synchronization *   * @author xiehejun * */ public class Synchronizedthread {& nbsp; class Bank { private int account = 100;&NB sp; public int getaccount () { &NB Sp Return account; } /** * with synchronization method * &N Bsp * @param money */ &NB Sp Public synchronized void Save (int money) { Account + = money; } /** * with synchronous code block * * @param money */ public void save1 ( int money) { synchronized (this) { &NBSP ; account + + money; } } } class Newthread implements Ru Nnable { private Bank bank; Public Newthread (Bank) { This.bank = bank; &NBSP ; } @Override Public V OID run () { &NBsp for (int i = 0; i < ten; i++) { &NBSP ; //bank.save1 (Ten); Bank.save (10) ; SYSTEM.OUT.PRINTLN (i + "account balance:" + bank.getaccount () ); } } } /** * creating threads, calling internal classes &NB Sp */ public void Usethread () { BANK bank = new Ban K (); Newthread new_thread = new Newthread (bank); &NBSP ; SYSTEM.OUT.PRINTLN ("Thread 1"); Thread thread1 = new Thread (new_thread); &NBSP Thread1.start (); SYSTEM.OUT.PRINTLN ("Thread 2"); &N Bsp Thread thread2 = new Thread (new_thread); Thread2.start () &nb Sp } public static void main (string[] args) { &NBSP ; Synchronizedthread st = new Synchronizedthread (); st.usethread (); &n Bsp } Copy code 3. Using special domain variables (volatile) for 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, 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 For example: In the example above, it is possible to synchronize threads by simply adding a volatile modifier to the account. code example:   Copy Code //give only the code to be modified, the rest of the code with the same class Bank { &NBSP ; //variables that need to be synchronized plus volatile private volatile int account = 100; public int getaccount () { return Accou nt; } //There is no need for synchronized & nbsp public void Save (int. money) { Account + = money; } } copy code NOTE: The non-synchronization problem in multi-threading mainly occurs in the Domain, if you let the domain itself avoid this problem, you do not need to modify the method that operates 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. Reentrantlock class is a re-entrant, mutual exclusion, the lock interface to achieve the locking, &NBSp It has the same basic behavior and semantics as using the Synchronized method and is fast, and extends its capabilities Reenreantlock classes are common methods that have: Reentrantlock (): Create a Reentrantlock instance lock (): Get lock &NBSP ; Unlock (): Release lock NOTE: Reentrantlock () There is also a construction method that can create a fair lock, but it is not recommended to use and, because it can significantly reduce program efficiency nbsp; For example: based on the above example, the rewritten code is: code example: copy code//give only the code to be modified, the rest of the code with the same class Bank { private int account = 100; //need to declare this lock Private lock lock = new Reentrantlock (); &nb Sp public int getaccount () { return account;   } //There is no need for synchronized &NBS P public void Save (int money) { Lock.lock (); &NBS P try{ Account + + MONEY;&NB Sp }finally{ & nbsp Lock.unlock (); } &N bsp; } } copy code &NBSP;&N bsp; NOTE: About the lock object and synchronized keyword selection: A. It is best to use one of the two java.util.concurrent packages provided by the mechanism, can help the user to handle all lock-related code. B. If the Synchronized keyword can be metSynchronized because it simplifies code C. If more advanced functionality is required, use the Reentrantlock class, and be aware that the lock is released in a timely manner, otherwise a deadlock will occur, usually in the finally code release lock 5. Using local variables for thread synchronization 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. This allows each thread to arbitrarily modify its own copy of the variable without affecting other threads. Common methods for ThreadLocal ThreadLocal (): Creating a thread-local variable Get (): Returns the value in the current thread copy of this thread's local variable initialvalue (): Returns the "initial value" of the current thread for this thread's local variables Set (T value): Sets the value in the current thread copy of this thread local variable to value For example: based on the above example, The modified code is: Code instance: copy code// Change the Bank class only, the rest of the code with the same public class bank{ //Use threadlocal class to manage the total Enjoy variable account private static threadlocal<integer> account = NEW threadlocal<integer> () { @Override &NBS P protected Integer initialvalue () { &NBSP ; return 100; } };&NB Sp public void Save (int. money) { ACC Ount.set (Account.get () +money); } Public int Getaccount () { return Account.get (); } } copy code NOTE: threadlocal and sync mechanism A.thread Both local and synchronization mechanisms are designed to address the same variable access violation in multiple threads. B. The former adopts a "space-for-time" approach, the latter using "time-for-space" approach : http://www.2cto.com/kf/201408/324061.html
How Java threads are synchronized