Nsthread/nsoperation of ios-Threading operations

Source: Internet
Author: User

1NSThread. Declaring a thread, starting a thread:(the first parameter declares the target class, the 2nd parameter declares the target method, and the 3rd parameter is the parameter of the method)

Nsthread *thread=[[nsthread alloc] Initwithtarget:selfselector: @selector (saleticketmethod:) object:@ "Thread--1"];[ Thread start];

2.IOS is thread-insecure like Android, which means that all UI updates must be done within the main thread, so that when we want to modify the view in another thread ,As follows:

(The first parameter is the target method, and the 2nd parameter is the parameter of the method and can only be 1.) )

[Self Performselectoronmainthread: @selector (updateview:) withobject:str Waituntildone:yes];

3. When different threads rob a common resource, a loads lock is required for the line, and the following is a system example of a ticket sale:

#import "CSZViewController.h" @interface Cszviewcontroller () {int _ticketnum; Nslock *_lock;} @end @implementation cszviewcontroller-(void) viewdidload{[super Viewdidload];}    -(void) Updateview: (NSString *) text{nsstring *str=[nsstring stringwithformat:@ "%@ \n%@", Self.textview.text,text]; Self.textview.text=str;}  -(void) Saleticketmethod: (NSString *) threadname{while (true) {if (_ticketnum>0) {[_lock            Lock];            NSString *str=[nsstring stringwithformat:@ "%@ thread votes:%d", threadname,_ticketnum];                        [Self Performselectoronmainthread: @selector (updateview:) withobject:str Waituntildone:yes];            _ticketnum--;            [_lock unlock];            if ([ThreadName isequaltostring:@ "thread--1"]) {[Nsthread sleepfortimeinterval:1.0];            }else{[Nsthread sleepfortimeinterval:2.0]; }}else {NSString *str=[nsstring stringwithformat:@ "The ticket is over!            %@ ", ThreadName];            [Self Performselectoronmainthread: @selector (updateview:) withobject:str Waituntildone:yes];        Break    }}}-(Ibaction) Threadclick: (ID) sender {_ticketnum=20;        Count the remaining votes//If there is a ticket, then sell//no stop; _lock=[[nslock alloc] init];    Nsthread *thread=[[nsthread alloc] initwithtarget:self selector: @selector (saleticketmethod:) object:@ "thread--1"];    Nsthread *thread1=[[nsthread alloc] initwithtarget:self selector: @selector (saleticketmethod:) object:@ "thread--2"];    [Thread start]; [Thread1 start];} @end


The use of---nsoperation is an elegant set of APIs that Apple has adopted for our multi-threaded implementation. It shields us from the same resources that we avoid robbing. The concept of thread queuing is also defined, and developers don't have to think about it.

Its usage is mainly divided into 3 points:

1, define the thread queue (set the number of threads running concurrently, because the thread is also consuming resources, analogous to the Java thread pool)

Nsoperationqueue *queue=[[nsoperationqueue alloc] init]; [Queue Setmaxconcurrentoperationcount:5];


2. Define an asynchronous thread. (again, the following parameters also declare the class where the threading method resides and the required method parameters)

Nsinvocationoperation *opera=[[nsinvocationoperation alloc]initwithtarget:self selector: @selector (OperaSaleMethod :) object:@ "Threading Operation 1"]; Nsinvocationoperation *opera2=[[nsinvocationoperation alloc]initwithtarget:self selector: @selector ( Operasalemethod:) object:@ "threading Operation 2"];

3. Put the queue into the thread. The thread task is automatically assigned through the queue.

[Queue Addoperation:opera]; [Queue Addoperation:opera2];

4. For the method of operation, use the same resource, do not need to do the lock processing

-(void) Operasalemethod: (NSString *) threadname{while    (true) {        if (_ticketnum>0) {                        if ([ThreadName isequaltostring:@ "thread Operation 1"]) {                [nsthread sleepfortimeinterval:2.0];            } else{                [Nsthread sleepfortimeinterval:1.2];            }                        NSString *str=[nsstring stringwithformat:@ "%@ thread votes:%d", threadname,_ticketnum];                        [Self Performselectoronmainthread: @selector (updateview:) withobject:str Waituntildone:yes];            _ticketnum--;        } else        {            nsstring *str=[nsstring stringwithformat:@ "%@ ticket ends! ", ThreadName];            [Self Performselectoronmainthread: @selector (updateview:) withobject:str Waituntildone:yes];            Break;}}}    


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.