iOS Multithreading implementation 2-nsthread

Source: Internet
Author: User

Nsthread is a lightweight multithreaded development, written in OC language, more object-oriented, and not very complex to use, but using nsthread requires you to manage the thread lifecycle. It is seldom used in iOS development to create a thread, but it is often used to do some delay, get the current thread, communicate between threads, and so on.

However, in terms of thread synchronization, it is troublesome to control the execution order of threads, there is a certain overhead for thread synchronization to lock data, and the creation of threads will increase the overhead of the system.

1 How to create

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

- (void) Rundemo: (NSString *) param {nsthread*current =[Nsthread CurrentThread]; NSLog (@"%@---%@ is running", param, current);}///Mode 1 automatically creates threads and starts automatically- (void) Threadcreateone {//execute Rundemo on another thread:[Self Performselectorinbackground: @selector (Rundemo:) Withobject:@" One"];}///Mode 2 starts the thread directly (automatically) when it is created- (void) Threadcreatetwo {[Nsthread detachnewthreadselector: @selector (rundemo:) totarget:self withobject:@" Both"];}///Mode 3 first creates the initialization thread, and then start opens the thread- (void) Threadcreatethree {nsthread*thread = [[Nsthread alloc] initwithtarget:self selector: @selector (Rundemo:)Object:@"three"]; //you can set the thread nameThread.Name =@"name"; //Open Thread[Thread start];}

The following is the test code, as well as the print results, we call the order is one->two->three, but the printing result is two->three->one, because the thread is only in the ready state after startup, the actual execution is to be scheduled by the CPU according to the current state, That is, the order of execution is unordered, which is also the feature of multithreading.

///Create a thread after tapping the screen- (void) Touchesbegan: (Nsset *) touches withevent: (Uievent *)Event{[Self threadcreateone];    [Self threadcreatetwo]; [Self threadcreatethree];} Printing results: -- ,- -  -: -:34.97401test[1183:76667]---<nsthread:0x7ff250e1c9a0>{number =3, name = (NULL)} isRunning -- ,- -  -: -:34.97401test[1183:76668] Three---<nsthread:0x7ff250e168a0>{number =4, name = name} isRunning -- ,- -  -: -:34.97401test[1183:76666] One---<nsthread:0x7ff250f406a0>{number =2, name = (NULL)} isRunning

2 Common functions

  Gets the current thread, gets the main thread, and determines whether the current thread is the main path.

// gets the current thread Nsthread *current = [Nsthread CurrentThread]; // get the main thread current = [Nsthread mainthread]; // to determine whether the current thread is the main path BOOL Ismain = [current Ismainthread];

To pause a thread, the following code is 2 ways to let the current thread sleep 5s

[Nsthread sleepfortimeinterval:5*date = [nsdate datewithtimeinterval:5  Sincedate:[nsdate Date]]; [Nsthread sleepuntildate:date];

Gets the state of the thread, respectively: executing, completed, canceled.

@property (readonly, getter=isexecuting); @property (readonly, getter=isfinished); Property (readonly, getter=iscancelled);

Executes a method on the specified thread (already existing thread), the main thread, and the current thread. This is commonly used for inter-thread communication , and they are nsobject extension methods that are convenient to use.

// executes the Rundemo: method on the specified thread, and the last yes represents: The following code blocks, and so on Rundemo: The next line of code is executed after the thread thread finishes executing, and no is blocked. So Rundemo: The order of execution with the next line of code is indeterminate [self performselector: @selector (rundemo:) Onthread:thread Withobject:nil Waituntildone:yes]; // execute Rundemo on Main thread: method, yes parameter above [Self performselectoronmainthread: @selector (rundemo:) Withobject:nil Waituntildone:yes]; // executing methods on the current thread [Self performselector: @selector (Run) Withobject:nil];

Exit thread

+ (void) exit;

Thread priority is related, the priority range is 0.0 ~ 1.0, the default is 0.5, the higher the value, the higher the priority level. When developing, the priority is seldom used, and special attention is needed if the priority is set and the lock is used to cause a priority rollover.

+ (double) threadpriority; + (BOOL) setthreadpriority: (double) p;

iOS Multithreading implementation 2-nsthread

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.