IOS multithreading implementation 2-NSThread, ios2-nsthread

Source: Internet
Author: User

IOS multithreading implementation 2-NSThread, ios2-nsthread

NSThread is a lightweight multi-threaded development. It is written in the OC language and is more object-oriented. It is not complicated to use. However, you need to manage the thread lifecycle by yourself when using NSThread. It is rarely used in iOS development to create a thread, but it is often used for some delayed operations, get the current thread, inter-thread communication, and so on.

However, in terms of thread synchronization, It is troublesome to control the thread execution sequence. The system overhead of Data Locking during thread synchronization and the overhead of the system is also increased when a thread is created.

1 Creation Method

There are multiple creation methods,-(void) runDemo :( NSString *) param; is the example method to be executed.

-(Void) runDemo :( NSString *) param {NSThread * current = [NSThread currentThread]; NSLog (@ "% @ --- % @ is running", param, current );} /// method 1 automatically creates a thread and automatically starts-(void) threadCreateOne {// execute runDemo: [self defined mselectorinbackground: @ selector (runDemo :) withObject: @ "One"];} // Method 2: After the thread is created, start it directly (automatically)-(void) threadCreateTwo {[NSThread detachNewThreadSelector: @ selector (runDemo :) toTarget: self withObject: @ "Two"];} // method 3: first create the initialization thread, and then start to enable the thread-(void) threadCreateThree {NSThread * thread = [[NSThread alloc] initWithTarget: self selector: @ selector (runDemo :) object: @ "Three"]; // you can set the thread name thread. name = @ "name"; // enable the thread [thread start];}

The following is the test code and the printed result. The call sequence is One-> Two-> Three, but the printed result is Two-> Three-> One, because the thread is only in the ready state after it is started, whether or not the actual execution should be scheduled by the CPU according to the current state, that is, the execution order is out of order, which is also a characteristic of multithreading.

/// Click the screen to create a thread (void) touchesBegan :( NSSet *) touches withEvent :( UIEvent *) event {[self threadCreateOne]; [self threadCreateTwo]; [self threadCreateThree];} print result: 16:27:34. 974 01 test [1183: 76667] Two --- <NSThread: 0x7ff250e1c9a0> {number = 3, name = (null)} is running2015-08-27 16:27:34. 974 01 test [1183: 76668] Three --- <NSThread: 0x7ff250e168a0> {number = 4, name = name} is running2015-08-27 16:27:34. 974 01 test [1183: 76666] One --- <NSThread: 0x7ff250f406a0> {number = 2, name = (null)} is running

2 common functions

  Obtain the current thread, obtain the main thread, and determine whether the current thread is the main thread.

// Obtain the current thread NSThread * current = [NSThread currentThread]; // obtain the main thread current = [NSThread mainThread]; // determine whether the current thread is the main thread BOOL isMain = [current isMainThread];

Pause the thread. The following code uses two methods to sleep the current thread for 5 seconds.

[NSThread sleepForTimeInterval:5];NSDate *date = [NSDate dateWithTimeInterval:5 sinceDate:[NSDate date]];[NSThread sleepUntilDate:date];

Obtain the status of the thread, which is in progress, completed, and canceled.

@property (readonly, getter=isExecuting) BOOL executing;@property (readonly, getter=isFinished)  BOOL finished;@property (readonly, getter=isCancelled) BOOL cancelled;

Execute methods on the specified Thread (existing thread), main thread, and current thread. This method is commonly used for inter-thread communication and is a NSObject extension method, which is convenient to use.

// Execute runDemo in the specified thread: method. The final YES indicates that the following code will be blocked. Wait until runDemo: After the thread finishes executing the method, will execute the next line of code below. If it is set to NO, it will not block. Then, runDemo: The execution sequence of the Code in the next line is unknown. [self defined mselector: @ selector (runDemo :) onThread: thread withObject: nil waitUntilDone: YES]; // run runDemo in the main thread: method. The "YES" parameter is the same as that of [self defined mselecw.mainthread: @ selector (runDemo :) withObject: nil waitUntilDone: YES]; // method of executing in the current thread [self defined mselector: @ selector (run) withObject: nil];

Exit thread

+ (void)exit;

Thread priority. The priority range is 0.0 ~ 1.0. The default value is 0.5. A greater value indicates a higher priority. During development, priority is rarely used. If the priority is set and the thread lock is used, the priority will be flipped, so you need to pay attention to it.

+ (double)threadPriority;+ (BOOL)setThreadPriority:(double)p;

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.