Feel every day is in a hurry, every day seems to be time is not enough, but so really want to hit the code when only to find that there are a lot of knowledge is not too skilled, so, people can not always feel self-good, there is time is that kind of self-feeling good mentality ruined their bright future!
Today we really are the end of the iOS course, but this does not mean that the end, but that there is a new beginning, entered a new stage, so efforts and struggle is the slightest can not be reduced, we will face is more severe test, friends together refueling Oh!
Now let me give you a brief introduction to the knowledge point we are talking about today.
Program: The executable file formed after the code was compiled (for example: *.app)
Process: Gets the resources that a program needs to run (for example: memory)
Threads: the smallest execution unit, allocating and dispatching resources
Note: A process has at least one thread (the main path)
So what is multithreading? As the name implies is high efficiency I would like to cite an example, if the program is a restaurant, restaurants need resources (such as houses, tables, etc.) by the process to obtain, the thread equivalent to the waiter, is the real performer, to allocate resources (arrange the customer to do that table, eat what meal), etc. Multi-threaded more attention should be to improve efficiency bar (personal understanding ha).
Let's give an example:
Now put a picture on the screen (Uiimageview) and a UIButton
Self.view.backgroundColor =[Uicolor Yellowcolor]; Self.iamgeview= [[Uiimageview alloc] initwithimage:[uiimage imagenamed:@"Taiji"]]; _iamgeview.center=Self.view.center; [Self.view Addsubview:_iamgeview]; [_iamgeview release]; [Nstimer scheduledtimerwithtimeinterval:0.1target:self selector: @selector (BEGIN) Userinfo:nil Repeats:yes]; UIButton*button =[UIButton Buttonwithtype:uibuttontypesystem]; Button.frame= CGRectMake (0,0, -, +); [Button Settitle:@"Start Moving Bricks ."Forstate:uicontrolstatenormal]; [Button addtarget:self action: @selector (Movebrick) forcontrolevents:uicontroleventtouchupinside]; [Self.view Addsubview:button];
One of the methods of Nstimer Association begins is to let him begin to spin, and the above mentioned Uiimageview is a global variable, because it is used at the following time, the method associated with Nstimer and button is attached below.
- (void) begin{[UIView beginanimations:@"Start Rotation"Context:null]; //2D Rotation//_iamgeview.transform = cgaffinetransformrotate (Self.iamgeView.transform, m_pi_4); //3D RotationSelf.iamgeView.layer.transform = Catransform3drotate (Self.iamgeView.layer.transform,-m_pi_4,0,0,1); [UIView commitanimations]; }- (void) movebrick{//cause the main thread to block for(inti =1; I <10000; i++) {NSString*string= [NSString stringWithFormat:@"finally moved%d fast bricks.", I]; NSLog (@"%@",string); }}
the Begin method mentioned above is one that moves on a two-dimensional plane, while the other is moving in three dimensions, where the rotation ( -m_pi_4, 0, 0, 1) The meaning of the parameter is the rotation angle, whether on the X, y, Z axis rotation, if you want to change direction, Just add the minus sign above the rotation angle to OK. But this has a disadvantage, he will cause the main thread block, that is, when the implementation of the brick, the main thread (the motion of the picture) will stop until the end of the move brick. Then you will certainly ask, how can achieve synchronous movement, good, I will explain the next approach for you, this practice is multi-threaded way, if you do not understand can ask me at any time, the code has comments below for everyone to plug in the code
Self.iamgeview = [[Uiimageview alloc] initwithimage:[uiimage imagenamed:@ "Taiji"];
_iamgeview.center = Self.view.center;
[Self.view Addsubview:_iamgeview];
[_iamgeview release];
UIButton *probutton = [UIButton buttonwithtype:uibuttontypesystem]; = CGRectMake (all); [Probutton settitle: @" Advanced Moving Bricks " Forstate:uicontrolstatenormal]; [Probutton addtarget:self Action: @selector (Movebrickwiththread) forcontrolevents:uicontroleventtouchupinside]; [Self.view Addsubview:probutton];
The associated methods are as follows:
- (void) movebrickwiththread{//Multi-threaded mode//1.NSObject Background Execution//automatically creates a thread (child thread) for you to execute code in the background//[Self performselectorinbackground: @selector (Movebrickpro) Withobject:nil]; //2.NSThread, System-provided threading class//created sub-threads//nsthread *thread = [[Nsthread alloc] initwithtarget:self selector: @selector (Movebrickpro) Object:nil];//Thread.Name = @ "yards nong 1";//[Thread start];//[Thread release]; //[Nsthread Mainthread];//NSLog (@ "Main thread:%@", [Nsthread Mainthread]);//[Nsthread CurrentThread];//NSLog (@ "Current thread:%@", [Nsthread CurrentThread]); //3.NSOperationQueue, Operation queue, automatically create a thread, Operation queue is nsoperation (Operation unit)//stack: Advanced back out//queue: FIFO//nsoperation, Operation unit, can only be executed once, is abstract classnsinvocationoperation*invocation = [[Nsinvocationoperation alloc] initwithtarget:self selector: @selector (Movebrickpro)Object: nil]; //Perform action (only once, execute in main thread)//[invocation start];//[invocation release];__block Rootviewcontroller *blockself =Self ; Nsblockoperation*block = [Nsblockoperation blockoperationwithblock:^{[Blockself Movebrickpro]; }]; //Create an action queue with a child thread from the queueNsoperationqueue *quera =[[Nsoperationqueue alloc] init]; //sets the maximum number of concurrent queues, which by default is-1, which means that the number of concurrent numbers is infinitely largeQuera.maxconcurrentoperationcount =1; //Add an Action unit to the queue[Quera addoperation:invocation]; [Quera Addoperation:block]; [Quera release]; [Invocation release]; [Nsthread Mainthread]; NSLog (@"primary-to-column:%@", [Nsoperationqueue mainqueue]); [Nsthread CurrentThread]; NSLog (@"Current queue:%@", [Nsoperationqueue currentqueue]); //Add the operating unit to the main queue, and the operating unit executes in the primary thread//Add the Operation unit to the sub-queue, and the grass error unit executes in the child thread}
- (void) movebrickpro{//the difference between the main thread and the child thread//1. Main thread takes up memory: 1M, sub-thread occupies memory: 512k//2. Child threads do not free memory and need to be manually freed pool//3. The main thread Nsrunloop automatically open, sub-thread nsrunloop default is closed, can not accept events, need to open manually//4. Updating the UI in a child thread may fail and need to update the UI in the main thread@autoreleasepool { for(inti =1; I < +; i++) {NSString*string= [NSString stringWithFormat:@"finally moved%d fast bricks.", I]; NSLog (@"%@",string); } //Nsrunloop, each thread has a nsrunloop to monitor and accept events//turn on the event loop for the child thread[[Nsrunloop Currentrunloop] run]; [Self Performselectoronmainthread: @selector (Refreshui) Withobject:nil Waituntildone:yes]; } [Nsthread Mainthread]; NSLog (@"main thread:%@", [Nsthread mainthread]); [Nsthread CurrentThread]; NSLog (@"Current thread:%@", [Nsthread CurrentThread]);}
?????? Next is today's last knowledge point that is the ultimate version of multithreading this time we come through a real life example to let everyone know more deeply about multithreading, presumably everyone knows the station ticket, if there is only one window, the station is not equal to explode, so this is similar to our multi-threading, Introduce multiple sub threads for management, first two are still the same. Add a button UIButton and a picture to the attempt controller and then let the button associate the method as follows (the top priority)
//Start Selling Tickets- (void) startsale{Currentticket= -; Salecount=0; //Create a ticket windowNsthread *windowone = [[Nsthread alloc] initwithtarget:self selector: @selector (Saleticket)Object: nil]; Windowone.name=@"A01"; Nsthread*windowtwo = [[Nsthread alloc] initwithtarget:self selector: @selector (Saleticket)Object: nil]; Windowtwo.name=@"B02"; //Start Ticketing[Windowone start]; [Windowone release]; [Windowtwo start]; [Windowtwo release];}- (void) saleticket{//multithreading can improve the performance, on the contrary, the cost of the looting of resources while(YES) {[Nsthread sleepfortimeinterval:0.2]; //Locking//[_lock lock]; if(Currentticket >0) {Currentticket--; Salecount++; NSLog (@"window:%@, sold%d of%d sheets left", [[Nsthread CurrentThread] name], Salecount, currentticket); } Else{NSLog (@"ticket has been sold out"); Break; }//[_lock unlock]; }}
You see, I commented out two words to the [_lock Lock],[_lock unlock], first of all, since it is a ticket, we must know how many tickets, and how much, so, before we start the time we first want to initialize two global variables, and assign values, here I assign the total number of votes is 100 , sold for 0. This is basically completed, but do not be careless, just now those two words if not add to the painting, the execution order will be wrong, the following for everyone to see an example:
This is part of the effect, we will find that there is a complete disorder, even the votes are negative and continue to sell, so those two words must be added, when a window began to sell tickets for the short time for their own, and then open after the sale, that is, do not let them rob each other resources, the following is the effect of the two words.
Note: But if you want to add those two words, you have to initialize a nslock and must remember to release, but his release and other not the same, to be extra cautious, slightly inattentive, the program will collapse, so should write to dealloc inside the safest.
By contrast you will certainly find this is clearly in order, no fighting the kind of posture, so friends, those two words must add oh, protect resources.
Today's class time I also made a small understanding of the GCD, and so tomorrow I will dig into the next and then give friends to share ha, today first came here, next week will start a new project, good tension has wood, but still anel not live in the heart that little excitement ah, refueling, come on!
iOS multithreading and its sentiment