------<a href= "http://www.itheima.com" target= "blank" >java training, Android training, iOS training,. NET training </a>, look forward to communicating with you! -------
Multi-threaded security issues
Cause: When when multiple statements are working on the same thread to share data, one thread executes only a portion of the multiple statements, has not finished executing, and another thread participates, resulting in a shared data error.
WORKAROUND: Statements that share data on multiple operations can only have one thread complete, and other threads cannot participate in execution during execution. The practice is to use synchronous code blocks:
Synchronized (object) {
Code that needs to be synchronized;
}
An object is like a lock, a thread that holds a lock can execute in synchronization, and a thread that does not have a lock will not get in even if it gets the execution of the CPU because there is no lock!
Prerequisites for synchronization:
1. There must be two or more threads of two
2. Must be multiple threads using the same lock
3. You must ensure that only one thread is in sync
Benefits: resolves multi-threaded security issues
Disadvantages: Multi-threaded to determine the lock, need to consume resources, slow running efficiency
The lock used by the synchronization function is this, and the lock used by the static synchronization function is the byte code of the current class, that is: class name.
Simple interest design mode for lazy loading:
Class singleton{
private static Singleton single = NULL;
Private Singleton () {}
public static Singleton getinstance () {
if (s==null) {
Synchronized (SINGELTON.CALSS) {
if (s==null) {
s = new Singleton ();
return s;
}
}
}
}
}
Dark Horse Programmer-Multi-Threading (ii)