A time-consuming operation inside the main thread causes the interface to block, so the time-consuming operations are typically put on child threads, such as network requests, thread sleep, loading files, and large numbers of operations. 1, do not put the time-consuming operation into the main thread. 2, do not put the code to modify the page to sub-thread (sub-thread modification page will not wait for timely update)
The first way to turn on a sub-thread nsthread //turn on a child thread [NsthreadDetachnewthreadselector:@selector(Createmouse)Totarget: SelfWithobject:Nil];
//return to main thread[selfperformselectoronmainthread:@selector(updateUI:)withobject: self. Mouse waituntildone:NO];
The second way to turn on a child thread Gcdgrand central Dispatch (GCD) is a multi-core programming solution developed by Apple, which itself creates a queue of threads that are listed as serial queues, getting the system-provided thread teams listed as parallel queues. //turn on a child thread
Dispatch_async(Dispatch_get_global_queue(Dispatch_queue_priority_default,0), ^{
NSData *data = [NSDataDatawithcontentsofurl:[Nsurlurlwithstring: Self.imagapaths[Indexpath.Row]]];
UIImage *image = [UIImageImagewithdata:d ATA];
//return to main thread
Dispatch_async(Dispatch_get_main_queue(), ^{
Cell.ImageView.Image= image;
[Cell Setneedslayout];
}); });
The third way to turn on a child thread nsoperation creates a thread queue that defaults to a parallel queue.- (void) Viewdidload
{
[Super Viewdidload];
//Way OneOpen a thread
nsoperation*OP1 = [[nsinvocationoperationAlloc]Initwithtarget: Selfselector:@selector(newthreadaction)Object:Nil];
//Mode twoOpen a thread
nsoperation*OP2 = [nsblockoperationBlockoperationwithblock:^{
for(intI=0; i<5; i++) {
[Nsthread Sleepfortimeinterval:. 5];
NSLog(@"Threads2--%d ", i);
}
}];
//Create thread queues, default created thread teams listed as parallel queues
Nsoperationqueue*myqueue = [[NsoperationqueueAlloc]Init];
//set the maximum number of concurrently executing threads
[MyqueueSetmaxconcurrentoperationcount:1];
//GiveOP1Add a dependencyDependentOP2
[OP1adddependency: OP2];
//add a thread to a queue, and the thread will not execute until it is added to the queue
[Myqueueaddoperation: OP1];
[Myqueueaddoperation: OP2];
}
- (void) newthreadaction{
for(intI=0; i<5; i++) {
[Nsthread Sleepfortimeinterval:. 5];
NSLog(@"Threads1--%d ", i);
}}
the difference between GCD and nsoperation1, GCD, the code is more concise, use more convenient, GCD more efficient, because belong to the C language syntax, the lower level. 2, Nsoperation, flexible control of the relationship between threads, you can set the number of simultaneous execution of threads. //sets the maximum number of simultaneous threads and, if set to 1, is the equivalent of thread serial execution[Myqueue setmaxconcurrentoperationcount:1]; //GiveOP1Add a dependencyDependentOP2, execute OP2 First, then execute OP1[OP1 adddependency: OP2];
Processes and Threads