IOS development keyword synchronized

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.