In the previous blog if the use of asynchronous requests, but also used to third-party things, there is no serious used in iOS multi-threaded things. In fact, multi-threaded things are still very important, if for the previous learning of the operating system of small partners, understand the multi-threaded things are relatively easy, today do a small demo to learn more about the multi-threaded in iOS things. Perhaps the following things will be more boring, but it is more practical.
Multi-threaded use or more, nonsense less said, the following two are the final results of our experiment today, should be relatively full, small partners from the figure to analyze the specific functions of it:
Function Description:
1, click the sync request picture, observe the whole UI changes, and click the Test button, Red will turn green.
2, Nsthread button, is the Nsthread way to create the thread and perform the appropriate action.
3, the block Operation button is to create the operation with block, and execute in the operation queue, the following is the invocation operation
4, serial is the serial queue in GCD, concurrent is the parallel queue in GCD
OK, the salted egg up here first, the code should go.
First, the preparatory stage
1. Whether you write with code, storyboard or Xib, first initialize the controls you want above to use the
2. Click the Test UI button to change the color of the label below:
1 //change the color of the lable and switch between the red and green colors2-(Ibaction) Taptestbutton: (ID) Sender {3 Static inti =1;4 if(i = =1) {5_testlabel.backgroundcolor =[Uicolor Redcolor];6i =0;7 }8 Else9 {Ten_testlabel.backgroundcolor =[Uicolor Greencolor]; Onei =1; A } - -}
3. Get the picture from the network and use the main thread to show the process call situation
1 //get picture data from Wang ' Lu2-(NSData *) Getimagedata3 {4 5_count + +;6 intCount =_count;7 8NSData *data;9[Nsthread Sleepfortimeinterval:0.5];Tendata =[NSData Datawithcontentsofurl:[nsurl urlwithstring:imageurl]; One ANSString *str = [NSString stringWithFormat:@"%d. Thread%@ complete", Count,[nsthread CurrentThread]]; - //The task of requesting data is resolved by another thread, so the contents of Logtextview are updated by the main thread, and only the main thread can update the UI - [Self performselectoronmainthread: @selector (updatetextviewwithstring:) withobject:str Waituntildone:yes]; the returndata; -}
4. The above uses the main thread to invoke the Updatetextviewwithstring method, because only the main thread can update Ui,updatetextviewwithstring: This method is responsible for displaying the execution information of the thread on the view, the code is as follows:
1 //Show picture requests on Viewcontroller2-(void) Updatetextviewwithstring: (NSString *) Str3 {4NSString *old_str = [NSString stringWithFormat:@"%@\n%@", _logtextview.text, str];5 6_logtextview.text =Old_str;7 //change the color of the label for easy observation8 [self taptestbutton:nil];9}
5. Load the requested picture onto the ImageView
1 // Update Picture 2 -(void) Updateimagewithdata: (NSData *) data3{4 UIImage *image = [UIImage imagewithdata:data]; 5 [_testimage setimage:image]; 6 }
6. Load the image, that is, the request data is displayed on the ImageView
1 // data is requested by other threads, and the UI is updated by the main thread 2 -(void) Loadimagewiththreadname: (NSString *) threadname3{4 [[Nsthread CurrentThread] setname:threadname]; 5 6 NSData *data = [self getimagedata]; 7 [Self performselectoronmainthread: @selector (updateimagewithdata:) withobject:data Waituntildone:yes]; 8 }
Second, through a variety of ways to
1. Synchronous request picture test, request data and update UI are placed in the main thread sequence execution, so that when the data is requested by the UI will be stuck, the code is as follows;
1 // Sync request picture, view blocked because the main thread is occupied, unable to update the view 2 -(ibaction) Tapbutton: (ID) sender {3 nsdata *data = [self getimagedata]; 4 [self updateimagewithdata:data]; 5 }
2.NSThread Create a thread test, using the Detachnewthreadselector method to create a new thread automatically starts and executes without calling the Start method. The code is as follows:
1 // Nsthread 2 -(ibaction) TapButton2: (ID) sender {3 // Click the button once to create a new thread request picture data 45 [nsthread detachnewthreadselector: @selector ( Loadimagewiththreadname:) totarget:self withobject:@ "nsthread"]; 6 }
For 3.NSInvocationOperation use, create a new call operation and then add it to the queue to execute, with the following code:
1 //nsinvocationoperation2-(Ibaction) Tapinvocationoperation: (ID) Sender {3 //instantiate a call operation to execute a data request4Nsinvocationoperation *invocationoperation = [[Nsinvocationoperation alloc] initwithtarget:self selector: @selector ( Loadimagewiththreadname:)Object:@"invocation"];5 6 //The above call operation needs to be placed in the call queue before execution7 //Create an action queue8Nsoperationqueue *operationqueue =[[Nsoperationqueue alloc] init];9 Ten //Put the above call operation in the operation queue, the queue will automatically open a thread to call the method we specified One [Operationqueue addoperation:invocationoperation]; A}
4.block operation, create a new block operation and add it to the queue to execute, the code is as follows:
1 //blockoperation2-(Ibaction) Tapblockoperation: (ID) Sender {3__weak __block Viewcontroller *copy_self =Self ;4 5 //Create Blockoperation6Nsblockoperation *blockoperation = [Nsblockoperation blockoperationwithblock:^{7[Copy_self Loadimagewiththreadname:@"Block"];8 }];9 Ten //Add to Action queue OneNsoperationqueue *operationqueue =[[Nsoperationqueue alloc] init]; A [Operationqueue addoperation:blockoperation]; - - //a different way the[Operationqueue addoperationwithblock:^{ -[Copy_self Loadimagewiththreadname:@"Block"]; - }]; - +}
Serial Queue in 5.GCD:
1 //Serial Queue2-(Ibaction) Tapgcdserialqueue: (ID) Sender {3 //Create a serial queue4dispatch_queue_t Serialqueue = Dispatch_queue_create ("Myserialqueue", dispatch_queue_serial);5 6 7__weak __block Viewcontroller *copy_self =Self ;8 //Asynchronous Execution Queue9Dispatch_async (Serialqueue, ^{Ten[Copy_self Loadimagewiththreadname:@"Serial"]; One }); A -}
Parallel queues in 6.GCD:
1 //Parallel Queues2-(Ibaction) Tapgcdconcurrentqueue: (ID) Sender {3 //Create a parallel queue4dispatch_queue_t Concurrentqueue = Dispatch_queue_create ("Myconcurrentqueue", dispatch_queue_concurrent);5__weak __block Viewcontroller *copy_self =Self ;6 //Asynchronous Execution Queue7Dispatch_async (Concurrentqueue, ^{8[Copy_self Loadimagewiththreadname:@"Concurrent"];9 });Ten One}
The above is the corresponding method of each button, the following is the result of the execution:
Iii. synchronization between threads (add a sync lock to our thread)
In the operating system to talk about multi-threading when a noun called dirty data, that is, multiple threads operation of the same resource caused by the following changes in code, so that the data problems, and then use a synchronous lock to solve the problem
1. There are two statements in the Getimagedata method (the 3rd method in heading one). This is used to display the thread's label. The markings above are not duplicated.
1 _count + +; 2 int count = _count;
Add a delay between the two statements, as follows:
_count + +; [Nsthread sleepfortimeinterval: 1 ]; int count = _count;
If run, there will be a lot of labels are repeated, one, __count is a member variable, multiple threads on this he operates, so there will be inconsistent labeling situation, below we add a synchronous lock
(1) with Nslock and synchronous lock, the code is as follows:
1 // by Nslock Locking 2 Lock ]; 3 _count + +; 4 [Nsthread sleepfortimeinterval:1]; 5 int count = _count; 6 [_lock unlock];
(2) via @synchronized Plus sync Lock, the code is as follows:
1 // by synchronized locking 2 int count; 3 @synchronized (self) {4 _count + +; 5 [Nsthread sleepfortimeinterval:1]; 6 Count = _count; 7 }
Before and after the lock operation effect is as follows:
Today the content of the blog is still very much, if the previous contact with Java multithreading, or other languages in the multi-threaded words, should not understand the problem.
Multi-Threading for iOS development