Static Config * instance =
Nil;
+ (Config *) Instance {
@ Synchronized (self ){
If (nil =
Instance ){
[Self new];
}
}
Return
Instance;
}
+ (Id) allocWithZone :( NSZone *) zone {
@ Synchronized (self ){
If (instance =
Nil ){
Instance = [super
AllocWithZone: zone];
Return instance;
}
}
Return nil;
}
In the above two examples, the keyword @ synchronized is used.
@ Synchronized indicates that this method is locked, which is equivalent to checking whether other threads (such as thread A) are running in this method. For example, B is using this method, if yes, run thread A after thread B using the synchronized method runs the method. If not, run it directly. It includes two usage methods: synchronized Method and synchronized block. @ Synchronized: The method controls the access to the class (generally used in a single instance in IOS): Each class instance corresponds to a lock, and each synchronized method must obtain the lock to call this method before execution, otherwise, thread blocking occurs. Once a method is executed, the lock is exclusive until the lock is released when the method is returned. Then, the blocked thread can obtain the lock, enter the executable status again. This mechanism ensures that at most one class is in the executable state at the same time, effectively avoiding access conflicts between class member variables (as long as all methods that may invoke classes are declared
Synchronized ).
Synchronized block:
@ Declare the synchronized block by using the synchronized keyword. Syntax:
@ Synchronized (syncObject ){}
The synchronized block is a code block in which the Code must obtain the lock of the object syncObject (as described earlier, it can be a class instance or class) before execution. The specific mechanism is described earlier. It is highly flexible because it can target any code block and can specify any locked object.