IOS-NSThread/NSOperation/GCD for thread operations
1NSThread. Declare the thread and start the thread: (the first parameter declares the target class, 2nd parameters declare the target method, and 3rd parameters are parameters of the method)
NSThread * thread = [[NSThread alloc] initWithTarget: selfselector: @ selector (saleTicketMethod :) object: @ "thread -- 1"]; [thread start];
2. IOS and Android are both thread-insecure, that is, all UI updates must be completed in the main thread. In this way, when we want to modify the View in another thread, as shown below:
(The first parameter is the target method. The first parameter is the parameter of the method and can only be one .)
[self performSelectorOnMainThread:@selector(updateView:) withObject:str waitUntilDone:YES];
3. When different threads snatch common resources, they need to lock the threads. The following is an example of a ticket selling system:
# 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) {[_ lo Ck lock]; NSString * str = [NSString stringWithFormat: @ "% @ thread count: % d", threadName, _ ticketNum]; [self defined mselecw.mainthread: @ selector (updateView :) withObject: str waitUntilDone: YES]; _ ticketNum --; [_ lock unlock]; if ([threadName is#tostring: @ "thread -- 1"]) {[NSThread sleepForTimeInterval: 1.0];} else {[NSThread sleepForTimeInterval: 2.0] ;}} else {NSString * str = [NSString stringWithFormat: @ "ticket sales are over! % @ ", ThreadName]; [self defined mselecw.mainthread: @ selector (updateView :) withObject: str waitUntilDone: YES]; break ;}}- (IBAction) threadClick :( id) sender {_ ticketNum = 20; // calculate the remaining number of votes. // if there is a ticket, the ticket is sold. // If not, the ticket is stopped. _ lock = [[NSLock alloc] init]; NSThread * thread = [[NSThread alloc] initWithTarget: self selector: @ selector (saleTicketMethod :) object: @ "thread -- 1"]; NSThread * thread1 = [[NSThread alloc] handler: self selector: @ selector (saleTicketMethod :) object: @ "thread -- 2"]; [thread start]; [thread1 start] ;}@ end
--- NSOperation is a simple API that Apple uses to implement multithreading. It blocks us from robbing the same resource. At the same time, the concept of thread queue is defined, so developers do not need to consider this.
Its usage is mainly divided into three points:
1. Define the thread Queue (set the number of threads running at the same time, because the open thread also needs to consume resources, similar to the JAVA thread pool)
NSOperationQueue *queue=[[NSOperationQueue alloc] init];[queue setMaxConcurrentOperationCount:5];
2. Define asynchronous threads. (Similarly, the following parameters are the classes that declare the thread method and the required method parameters)
NSInvocationOperation * opera = [[NSInvocationOperation alloc] initWithTarget: self selector: @ selector (operator :) object: @ "thread operation 1"]; NSInvocationOperation * opera2 = [[NSInvocationOperation alloc] Handler: self selector: @ selector (operaSaleMethod :) object: @ "thread operation 2"];
3. Put the queue into the thread. The thread task is automatically allocated through the queue.
[queue addOperation:opera];[queue addOperation:opera2];
4. You do not need to lock the same resource for the operation method.
-(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 count: % d ", threadName, _ ticketNum]; [self defined mselecw.mainthread: @ selector (updateView :) withObject: str waitUntilDone: YES]; _ ticketNum --;} els E {NSString * str = [NSString stringWithFormat: @ "% @ end of ticket sales! ", ThreadName]; [self defined mselecw.mainthread: @ selector (updateView :) withObject: str waitUntilDone: YES]; break ;}}}
GCD is a set of APIs that support multi-thread Development written in C language. Its model is similar to Operation, and the concept of group is added on this basis, A notification trigger mechanism is provided after all groups are completed.
1. Define a queue
//#define DISPATCH_QUEUE_PRIORITY_HIGH 2 //#define DISPATCH_QUEUE_PRIORITY_DEFAULT 0 //#define DISPATCH_QUEUE_PRIORITY_LOW (-2) //#define DISPATCH_QUEUE_PRIORITY_BACKGROUND INT16_MIN dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
2. Define a group
dispatch_group_t group=dispatch_group_create();
3. Define asynchronous tasks and add them to the queue
Dispatch_group_async (group, queue, ^ {[self gcdSaleMethod: @ "thread operation 1"] ;}); dispatch_group_async (group, queue, ^ {[self gcdSaleMethod: @ "thread operation 2"] ;});
4. Receive notifications from queues
Dispatch_group_notify (group, queue, ^ {NSLog (@ "thread operation completed ");});
The log shows that the content in the block is called back only when all threads are finished.
15:08:38. 982 ThreadSample01 [5256: 4007] thread operation 2 ticket sales ended! 15:08:39. 037 ThreadSample01 [5256: 1903] thread operation 1 ticket sales ended! 15:08:39. 042 ThreadSample01 [5256: 4007] thread operation completed