The role of @synchronized () is to create a mutex that ensures that no other thread modifies the self object at the same time, and that it acts as a thread protection and is generally used in common variables, such as singleton mode or static variables of an operation class.
Example One:// implementation of a single case Student.h # Import < foundation/foundation.h> @ Interface << Span style= "font-style:normal; Font-variant:normal; Font-weight:normal; Font-family:menlo ">nscopying, NSMutableCopying > @ Propertynonatomic, copy) NSString *name; //1, declare a class method in the H file to initialize the instance + (ID) sharestudent; @end STUDENT.M #import "Student.h" / /2 , in .m file first declare a static Modified object, this object is a null pointer at this time static Student *stu = nil; @implementation Student //3, Implementing A class method declared in. h + (ID) sharestudent{ // Avoid the drawbacks of multi-threaded operation (mutual exclusion lock) @synchronized(Self){
If(Stu==Nil) {
Stu= [[Student alloc ]init }
return stu } }4AvoidAllocCreates a new object, so you want to overrideAllocwithzoneMethod
+(Instancetype) Allocwithzone: (struct_nszone*) zone{
If(Stu==Nil) {
Stu = [super Allocwithzone: zone];
}
return Stu; }5To avoid copying and creating new objects, we need to rewriteCopywithzoneAndMutablecopywithzoneMethod
-(ID) Copywithzone: (nszone *) zone{
return Stu; }-(ID) Mutablecopywithzone: (nszone *) zone{
return Stu; }@endExample Two:// implementation of the operation class
# import "NetworkManager.h"
Static NetworkManager *Network = nil;
@implementation NetworkManager
+ (NetworkManager *)getnetworkinstance{
@synchronized(self) {
if (nil = = Network) {
Network = [[NetworkManager alloc] init];
{
}
return network;
}
Summary of usage of @synchronized (self)