The first: the use of the synchronized keyword
Since each object of the java has a built-in lock, when using this keyword modification methods, built-in locks protect the entire method. Before calling this method need to get the built-in lock, otherwise it is blocked.
Note: synchronized keyword static methods can also be modified, if the static method call at this time, it will lock the entire class.
Synchronization is a high-cost operation, and therefore should be minimized sync. It is usually not necessary to synchronize the entire method synchronized code block synchronization using the key code.
1. The synchronization method: a method to increase after the synchronized modifier can make it a synchronization method, this method can be static and non-static methods, but can not be abstract method abstract class, nor is the interface method interface.
When performing thread synchronization method is having an exclusive. When any one thread to enter into any of a synchronization method of an object, the object of all the synchronization method are locked up,
In the meantime, any other thread can access any object of a synchronization method, until this thread has finished the implementation of the synchronization method it calls and exit from,
Causing it to release the lock of the object after synchronization. After an object is locked a thread, all other threads are asynchronous method can access the object.
2. The sync block: sync blocks is performed by locking a specified object included in the block sync code synchronization; and this method is a synchronization method in the block synchronization code, and the locking of the object in this case is the synchronization the main object method belongs to itself.
If this method is static synchronous way to do that? Then the thread lock on the object of this class is not, nor is it
The class itself, but corresponding to objects of this class java.lang.Class type. Interactions among sync block synchronization method and confined between the same object, it is limited only by the static method of synchronizing the class it belongs to other static synchronization method, with the instance (object) of this class does not matter.
If an object has both synchronous method, another synchronized block, then when any of a synchronized method or synchronized block is executed a thread, the object is locked, other threads can not access the synchronization method this object at this time, sync block can not be executed.
synchronized keyword for protecting shared data. Please note that "shared data", you have to distinguish between what data is shared data.
package com.gcc.interview.synchro; /** * Create a thread * @author gcc * * March 9, 2018 */ public class MybanRunnable implements Runnable{ private Bank bank; public MybanRunnable(Bank bank) { this.bank = bank; } @Override public void run() { for(int i=0;i<10;i++) { bank.save1(100); System.out.println ( "Account Balance is ---" + bank.getAccount ()); } } }
package com.gcc.interview.synchro; /** * Examples of bank deposits * @author gcc * * March 9, 2018 */ class Bank{ private int account = 100; public int getAccount() { return account; } // synchronization method public the synchronized void Save ( int Money) { account+=money; } public void save1 ( int Money) { // synchronized block the synchronized ( the this ) { account+=money; } } public void userThread() { Bank bank = new Bank(); MybanRunnable my1 = new MybanRunnable(bank); System.out.println ( "Thread 1" ); Thread th1 = new Thread(my1); th1.start(); System.out.println ( "Thread 2" ); Thread th2 = new Thread(my1); th2.start(); } }
The second: wait and notify
wait (): make a thread in a wait state, and releases the lock held by the object.
sleep (): make a running thread in a sleep state, it is a static method call this method to capture InterruptedException exception.
notify (): wake up a thread in a wait state, noting that at the time this method is called, does not exactly wake up one thread wait state, but which is determined by the JVM thread wakes up, but not by priority.
Allnotity (): wake up a thread into a wait state at all, note that not all wake up threads to lock an object, but let them compete.
Third: the use of special domain variable volatile implement thread synchronization
1.volatile keyword provides access to the domain of a free variable lock mechanism;
2. Use the volatile region equivalent to modify the virtual machine to tell this field may be updated by other threads;
3. therefore necessary to recalculate each use of the domain , rather than using register values;
4.volatile not provide any atomic operation, it can not be used to modify the final type of variable;
for example:
in the example above them, just in front of the account plus volatile modifications can implement thread synchronization.
// given only to modify the code, with the rest of the code and the class Bank { // variables need to be synchronized plus volatile Private volatile int Account = 100 ; public int getAccount() { return account; } // this is no longer required the synchronized public void Save ( int Money) { account += money; } }
Fourth: Use reentrant locks for thread synchronization
Added a java.util.concurrent package in JavaSE5.0 in support synchronization.
ReentrantLock class is reentrant, exclusive, to achieve lock Lock interface, it is fast and using synchronized methods have the same basic behavior and semantics, and its ability to expand.
Common method ReenreantLock class are:
ReentrantLock (): Create an instance of ReentrantLock
lock (): get the lock
unlock (): release the lock
Note: ReentrantLock () can also create a fair lock construction method, but can significantly reduce the efficiency program, not recommended
private int account = 100;
private ReentrantLock lock = new ReentrantLock();
public int getAccount() { return account; } // synchronization method public void Save ( int Money) { lock.lock(); try { account+=money; } finally { lock.unlock(); } }
Note: Lock on selected object and the synchronized keyword:
A best two are not in the java.util.concurrent package uses a mechanism provided to help users deal with all the lock code.
. b If the synchronized keyword to meet the needs of users, use synchronized, because it can simplify the code;
. c If you need more advanced features, use ReentrantLock class, this time to pay attention to timely release the lock, otherwise there will be a deadlock, usually lock in a finally released.
Fifth: Use local variables to implement thread synchronization
ThreadLocal (): Creates a thread local variable get (): Returns the value of this thread-local copy of the current thread initialValue (): Returns the current thread-local variable thread "initial value" SET (T value): this value is set to the current copy of the thread in the thread-local variable to value
// change only Bank class, and the rest of the code with the public class {Bank // Use ThreadLocal class manages shared variable Account Private static ThreadLocal <Integer> = Account new new ThreadLocal <Integer> () { @Override protected Integer initialValue(){ return 100; } };
public void save(int money){ account.set(account.get()+money); }
public int getAccount(){ return account.get(); } }
Sixth: blocking queue implementation using thread synchronization
In front of five kinds of thread synchronization method is the underlying implementation of sync, but we are actually in development, it should be as far away from the underlying structure.
Use javaSE5.0 version of the new java.util.concurrent package will help to streamline development. This section primarily using LinkedBlockingQueue <E> to synchronize threads LinkedBlockingQueue <E> is an optionally-blocking queue based on the connected nodes.
Queues are FIFO order (FIFO), the queue will be explained in detail later on ~ LinkedBlockingQueue class common method LinkedBlockingQueue (): Creates a capacity of Integer.MAX_VALUE LinkedBlockingQueue put (E e):
Adding an element in the tail, if the queue is full blocking size (): Returns the number of elements take the queue (): removes and returns the first element of the team, if the queue is empty blocking code examples: businesses realize the production of goods and commodities trading synchronization
Note: BlockingQueue <E> defines a common method of blocking queue, and three in particular additive element method, we should pay more attention when the queue is full:
add () method throws an exception
the offer () method returns false
put () method blocks
Seventh: implement thread synchronization with atomic variables
The root cause lies in the need to use thread synchronization operation is not ordinary variables atoms.
So what is an atomic operation it? Atomic operation refers to the value of the variable read, modify variable values for variables as a whole that is to operate - these types of behavior are either performed simultaneously, or none of them is complete.
Providing tools create atomic types of variables in the java util.concurrent.atomic package, simplifies the use of such thread synchronization. Wherein AtomicInteger table can be updated atomically int value,
Can be used in applications (such as atomically increment a counter), but can not be used to replace Integer; scalable Number, tools and utilities that allows the opportunity to process the digital uniform access classes.
AtomicInteger class common methods:
AtomicInteger ( int initialValue): Creates a new with the given initial value of AtomicIntegeraddAddGet ( int Dalta): Atomically given value and the current value is added get (): Get the current value
Code examples:
Bank-based change only the remaining code with the first example above
class Bank { private AtomicInteger account = new AtomicInteger(100);
public AtomicInteger getAccount() { return account; }
public void save(int money) { account.addAndGet(money); } }