Nsthread (main thread, child thread) in iOS

Source: Internet
Author: User

#import"AppDelegate.h"@interface appdelegate () {Nsinteger _totaltickests;} @property (nonatomic, retain) Nslock*Lock; @end @implementation appdelegate- (void) Task1 {NSLog (@"Current thread:%@, whether it is the main thread:%d", [Nsthread currentthread],[[nsthread CurrentThread] ismainthread]); //The current task is completed in the main thread, and no subsequent code is executed until it is completed     for(Longi =0; I <=10000000; i++) {NSLog (@"%ld", i); }}- (void) Task2 {NSLog (@"Current thread:%@, whether it is the main thread:%d", [Nsthread currentthread],[[nsthread CurrentThread] ismainthread]); //The current task is completed in the main thread, and no subsequent code is executed until it is completed     for(Longi =0; I <= -; i++) {NSLog (@"I'm a la La."); }}- (void) task3{NSLog (@" Quack Gaga");}- (void) task4{NSLog (@"Blue Euro 4");}- (void) task5{NSLog (@"iOS5");}/** * The system by default turns on the event loop in the main thread, continuously listens for user interaction events, but does not have an event loop when it is turned on in a child thread. Runloop*/- (void) starttime{@autoreleasepool {//Turn on Timer[Nstimer Scheduledtimerwithtimeinterval:0.5target:self selector: @selector (TASK3) Userinfo:nil Repeats:yes]; //when the event loop is turned on in a child thread, the timer is able to perform the task repeatedly with the event loop.[[Nsrunloop Currentrunloop] run]; }}/*programs: Each application installed on a mobile device is a program process: Every application that is running is a process, and the process is equivalent to a task. Thread: The unit fragment that executes a task is called a thread, which is the real performer of the task, but the system defaults to a thread to do the task,   Threads are the main thread, and in order to improve the user experience, we need to hand over the time-consuming operations to the child threads. *///Buy Tickets- (void) Selltickets: (NSString *) name{@autoreleasepool { while(YES) {[Self.Lock Lock]; if(_totaltickests >0) {                //Buy Tickets_totaltickests--; NSLog (@"%@ Sell ticket, number of votes left%ld", name, _totaltickests); }Else{NSLog (@"%@ sold out.", name);  Break; } [self.Lockunlock]; }    }}//thread deadlock: Critical resources reduce the process of unlocking, it is easy to cause a deadlock, one thread waits for another thread to release the resource, but the previous thread is missing the unlock process, causing the latter thread to remain in the waiting state//thread Mutex: When multiple threads access the same resource, one thread accesses, the other threads should wait, and the lock is required at this time-(BOOL) Application: (UIApplication *) application didfinishlaunchingwithoptions: (Nsdictionary *) launchoptions {Self.window=[[[UIWindow alloc] initwithframe:[[uiscreen mainscreen] bounds]] autorelease]; //NSLog (@ "Current thread:%@, whether it is the main thread:%d", [Nsthread currentthread],[[nsthread CurrentThread] ismainthread]); //initial number of votes_totaltickests = -; //Create a lockSelf .Lock=[[[ Nslock alloc] init] autorelease]; //Windows 1[Nsthread detachnewthreadselector: @selector (selltickets:) totarget:self withobject:@"Zhang"]; //Windows 2[Nsthread detachnewthreadselector: @selector (selltickets:) totarget:self withobject:@"Kim Fung"]; //[self task1]; //for time-consuming operations, the threading is done, and the main thread can still handle user interaction and interface changes//1. Create a child thread the first way, using the threading class Nsthread//[Nsthread detachnewthreadselector: @selector (TASK1) totarget:self Withobject:nil]; //2. Creating a child thread the second way, using the threading class, requires a manual open//nsthread *thread = [[Nsthread alloc] initwithtarget:self selector: @selector (TASK1) Object:nil];//    //[Thread start];//Open Thread//    //    //Release//[Thread release]; //3. Create a child thread the third way, using the method provided by NSObject//[Self performselectorinbackground: @selector (downloadimage) Withobject:nil]; //Main thread Timer//[Nstimer scheduledtimerwithtimeinterval:0.5 target:self selector: @selector (TASK3) Userinfo:nil Repeats:yes]; //Create a sub-thread, turn on the timer//[Self performselectorinbackground: @selector (startTime) Withobject:nil]; //Uiimageview *imageview = [[Uiimageview alloc] Initwithframe:[uiscreen mainscreen].bounds];//Imageview.tag = +;//Imageview.backgroundcolor = [Uicolor cyancolor];//[Self.window Addsubview:imageview];//[ImageView release]; //4. Create a child thread the fourth way, create love for your task queue, the task pair column will be the task in the queue, reasonably arrange the child threads to complete the task. //Create a Task 1//nsinvocationoperation *OP1 = [[Nsinvocationoperation alloc] initwithtarget:self selector: @selector (TASK4) object:   NIL]; //nsinvocationoperation *op2 = [[Nsinvocationoperation alloc] initwithtarget:self selector: @selector (TASK5) object:    NIL]; //Create a Task 2//nsblockoperation *OP1 = [Nsblockoperation blockoperationwithblock:^{//for (int i = 0; i < i++) {//NSLog (@ "Frank is ....");//        }//    }];//    //nsblockoperation *op2 = [Nsblockoperation blockoperationwithblock:^{//for (int i = 0; i < i++) {//NSLog (@ "What do you say?.");//        }//    }]; //Create a task queue, add a task to the task queue//nsoperationqueue *quene = [[Nsoperationqueue alloc] init];//    //1. Implement thread synchronization The first way, set the maximum number of concurrency//[Quene setmaxconcurrentoperationcount:1]; //2. The second way to implement thread synchronization, add dependencies//[Op2 ADDDEPENDENCY:OP1]; //[Quene ADDOPERATION:OP1]; //[Quene ADDOPERATION:OP2]; //Release//[OP1 release]; //[OP2 release]; //[Quene release];Self.window.backgroundColor=[Uicolor Redcolor];    [Self.window makekeyandvisible]; returnYES;}/** thread synchronization: Thread Concurrency: There is no relationship between tasks and tasks, the first thread to execute, and possibly the last task to complete.*//** The main thread jumps to the child thread to perform the task: Create the sub-thread directly, perform the corresponding time-consuming task to jump to the main thread to perform the task: for the interface refresh operation, by the main thread operation, using Performselectoronmainthread::: Operation*///Download Image- (void) downloadimage{//The child thread does not automatically release the pool, and the Traverse constructor internal operation is autorelease to manage memory, so you need to add the auto-free pool yourself@autoreleasepool {[Nstimer scheduledtimerwithtimeinterval:0.5target:self selector: @selector (TASK3) Userinfo:nil Repeats:yes]; //GET request, synchronous connection//1. Creating URL String ObjectsNSString *str =@"http://image.zcool.com.cn/56/13/1308200901454.jpg"; //2. Create a Nsurl objectNsurl *url =[Nsurl Urlwithstring:str]; //3. Create a Request objectNsurlrequest *request =[Nsurlrequest Requestwithurl:url]; //4. ConnectNSData *data =[nsurlconnection sendsynchronousrequest:request returningresponse:nil Error:nil]; UIImage*image =[UIImage Imagewithdata:data]; //If you want to refresh the UI (interface), modify the interface, should be referred to the main thread processing//The child thread jumps to the main thread, executes the task[Self performselectoronmainthread: @selector (referenceui:) withobject:image Waituntildone:yes]; //Waituntildone: Whether to wait for completion//If you have more than one parameter, you can put multiple arguments into a dictionary or an array, Withobject: to a dictionary or an array.    }        }- (void) Referenceui: (UIImage *) image{Uiimageview*imageview = (Uiimageview *) [Self.window Viewwithtag: -]; Imageview.image=image;}- (void) dealloc{Self.window=Nil; Self.Lock=Nil; [Super Dealloc];} @end

Nsthread (main thread, child thread) in iOS

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.