大家都知道,在开发过程中应该尽可能减少用户等待时间,让程序尽可能快的完成运算。可是无论是哪种语言开发的程序最终往往转换成汇编语言进而解释成机器码来执行。但是机器码是按顺序执行的,一个复杂的多步操作只能一步步按顺序逐个执行。改变这种状况可以从两个角度出发:对于单核处理器,可以将多个步骤放到不同的线程,这样一来用户完成UI操作后其他后续任务在其他线程中,当CPU空闲时会继续执行,而此时对于用户而言可以继续进行其他操作;对于多核处理器,如果用户在UI线程中完成某个操作之后,其他后续操作在别的线程中继续执行,用户同样可以继续进行其他UI操作,与此同时前一个操作的后续任务可以分散到多个空闲CPU中继续执行(当然具体调度顺序要根据程序设计而定),及解决了线程阻塞又提高了运行效率。苹果从iPad2 开始使用双核A5处理器(iPhone中从iPhone 4S开始使用),A7中还加入了协处理器,如何充分发挥这些处理器的性能确实值得思考。今天将重点分析iOS多线程开发:
当用户播放音频、下载资源、进行图像处理时往往希望做这些事情的时候其他操作不会被中断或者希望这些操作过程中更加顺畅。在单线程中一个线程只能做一件事情,一件事情处理不完另一件事就不能开始,这样势必影响用户体验。早在单核处理器时期就有多线程,这个时候多线程更多的用于解决线程阻塞造成的用户等待(通常是操作完UI后用户不再干涉,其他线程在等待队列中,CPU一旦空闲就继续执行,不影响用户其他UI操作),其处理能力并没有明显的变化。如今无论是移动操作系统还是PC、服务器都是多核处理器,于是“并行运算”就更多的被提及。一件事情我们可以分成多个步骤,在没有顺序要求的情况下使用多线程既能解决线程阻塞又能充分利用多核处理器运行能力。
下图反映了一个包含8个操作的任务在一个有两核心的CPU中创建四个线程运行的情况。假设每个核心有两个线程,那么每个CPU中两个线程会交替执行,两个CPU之间的操作会并行运算。单就一个CPU而言两个线程可以解决线程阻塞造成的不流畅问题,其本身运行效率并没有提高,多CPU的并行运算才真正解决了运行效率问题,这也正是并发和并行的区别。当然,不管是多核还是单核开发人员不用过多的担心,因为任务具体分配给几个CPU运算是由系统调度的,开发人员不用过多关心系统有几个CPU。开发人员需要关心的是线程之间的依赖关系,因为有些操作必须在某个操作完成完才能执行,如果不能保证这个顺序势必会造成程序问题。
在iOS中每个进程启动后都会建立一个主线程(UI线程),这个线程是其他线程的父线程。由于在iOS中除了主线程,其他子线程是独立于Cocoa Touch的,所以只有主线程可以更新UI界面(新版iOS中,使用其他线程更新UI可能也能成功,但是不推荐)。iOS中多线程使用并不复杂,关键是如何控制好各个线程的执行顺序、处理好资源竞争问题。常用的多线程开发有三种方式:
1.NSThread
2.NSOperation
3.GCD
三种方式是随着iOS的发展逐渐引入的,所以相比而言后者比前者更加简单易用,并且GCD也是目前苹果官方比较推荐的方式(它充分利用了多核处理器的运算性能)。做过.Net开发的朋友不难发现其实这三种开发方式 刚好对应.Net中的多线程、线程池和异步调用,因此在文章中也会对比讲解。
NSThread是轻量级的多线程开发,使用起来也并不复杂,但是使用NSThread需要自己管理线程生命周期。可以使用对象方法+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument直接将操作添加到线程中并启动,也可以使用对象方法- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(id)argument 创建一个线程对象,然后调用start方法启动线程。
在资源下载过程中,由于网络原因有时候很难保证下载时间,如果不使用多线程可能用户完成一个下载操作需要长时间的等待,这个过程中无法进行其他操作。下面演示一个采用多线程下载图片的过程,在这个示例中点击按钮会启动一个线程去下载图片,下载完成后使用UIImageView将图片显示到界面中。可以看到用户点击完下载按钮后,不管图片是否下载完成都可以继续操作界面,不会造成阻塞。
<span style="color: green;">// // NSThread实现多线程 // MultiThread // // Created by Kenshin Cui on 14-3-22. // Copyright (c) 2014年 Kenshin Cui. All rights reserved. // </span><span style="color: blue;">#import </span><span style="color: rgb(163, 21, 21);">"KCMainViewController.h" </span><span style="color: black;">@</span><span style="color: blue;">interface </span><span style="color: black;">KCMainViewController (){ UIImageView *_imageView; } @end @implementation KCMainViewController - (</span><span style="color: blue;">void</span><span style="color: black;">)viewDidLoad { [super viewDidLoad]; [self layoutUI]; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 界面布局 -(</span><span style="color: blue;">void</span><span style="color: black;">)layoutUI{ _imageView =[[UIImageView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame]; _imageView.contentMode=UIViewContentModeScaleAspectFit; [self.view addSubview:_imageView]; UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame=CGRectMake(50, 500, 220, 25); [button setTitle:@</span><span style="color: rgb(163, 21, 21);">"加载图片" </span><span style="color: black;">forState:UIControlStateNormal]; </span><span style="color: green;">//添加方法 </span><span style="color: black;">[button addTarget:self action:@selector(loadImageWithMultiThread) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 将图片显示到界面 -(</span><span style="color: blue;">void</span><span style="color: black;">)updateImage:(NSData *)imageData{ UIImage *image=[UIImage imageWithData:imageData]; _imageView.image=image; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 请求图片数据 -(NSData *)requestData{ </span><span style="color: green;">//对于多线程操作建议把线程操作放到@autoreleasepool中 </span><span style="color: black;">@autoreleasepool { NSURL *url=[NSURL URLWithString:@</span><span style="color: rgb(163, 21, 21);">"http://images.apple.com/iphone-6/overview/images/biggest_right_large.png"</span><span style="color: black;">]; NSData *data=[NSData dataWithContentsOfURL:url]; </span><span style="color: blue;">return </span><span style="color: black;">data; } } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 加载图片 -(</span><span style="color: blue;">void</span><span style="color: black;">)loadImage{ </span><span style="color: green;">//请求数据 </span><span style="color: black;">NSData *data= [self requestData]; </span><span style="color: green;">/*将数据显示到UI控件,注意只能在主线程中更新UI, 另外performSelectorOnMainThread方法是NSObject的分类方法,每个NSObject对象都有此方法, 它调用的selector方法是当前调用控件的方法,例如使用UIImageView调用的时候selector就是UIImageView的方法 Object:代表调用方法的参数,不过只能传递一个参数(如果有多个参数请使用对象进行封装) waitUntilDone:是否线程任务完成执行 */ </span><span style="color: black;">[self performSelectorOnMainThread:@selector(updateImage:) withObject:data waitUntilDone:YES]; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 多线程下载图片 -(</span><span style="color: blue;">void</span><span style="color: black;">)loadImageWithMultiThread{ </span><span style="color: green;">//方法1:使用对象方法 //创建一个线程,第一个参数是请求的操作,第二个参数是操作方法的参数 // NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector(loadImage) object:nil]; // //启动一个线程,注意启动一个线程并非就一定立即执行,而是处于就绪状态,当系统调度时才真正执行 // [thread start]; //方法2:使用类方法 </span><span style="color: black;">[NSThread detachNewThreadSelector:@selector(loadImage) toTarget:self withObject:nil]; } @end </span>
运行效果:
程序比较简单,但是需要注意执行步骤:当点击了“加载图片”按钮后启动一个新的线程,这个线程在演示中大概用了5s左右,在这5s内UI线程是不会阻塞的,用户可以进行其他操作,大约5s之后图片下载完成,此时调用UI线程将图片显示到界面中(这个过程瞬间完成)。另外前面也提到过,更新UI的时候使用UI线程,这里调用了NSObject的分类扩展方法,调用UI线程完成更新。
上面这个演示并没有演示多个子线程操作之间的关系,现在不妨在界面中多加载几张图片,每个图片都来自远程请求。
大家应该注意到不管是使用+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument、- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(id)argument 方法还是使用- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait方法都只能传一个参数,由于更新图片需要传递UIImageView的索引和图片数据,因此这里不妨定义一个类保存图片索引和图片数据以供后面使用。
KCImageData.h
<span style="color: green;">// // KCImageData.h // MultiThread // // Created by Kenshin Cui on 14-3-22. // Copyright (c) 2014年 Kenshin Cui. All rights reserved. // </span><span style="color: blue;">#import </span><span style="color: rgb(163, 21, 21);"><Foundation/Foundation.h> </span><span style="color: black;">@</span><span style="color: blue;">interface </span><span style="color: black;">KCImageData : NSObject </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 索引 @</span><span style="color: blue;">property </span><span style="color: black;">(nonatomic,assign) </span><span style="color: blue;">int </span><span style="color: black;">index; </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 图片数据 @</span><span style="color: blue;">property </span><span style="color: black;">(nonatomic,strong) NSData *data; @end</span>
接下来将创建多个UIImageView并创建多个线程用于往UIImageView中填充图片。
KCMainViewController.m
<span style="color: green;">// // NSThread实现多线程 // MultiThread // // Created by Kenshin Cui on 14-3-22. // Copyright (c) 2014年 Kenshin Cui. All rights reserved. // </span><span style="color: blue;">#import </span><span style="color: rgb(163, 21, 21);">"KCMainViewController.h" </span><span style="color: blue;">#import </span><span style="color: rgb(163, 21, 21);">"KCImageData.h" </span><span style="color: blue;">#define </span><span style="color: black;">ROW_COUNT 5 </span><span style="color: blue;">#define </span><span style="color: black;">COLUMN_COUNT 3 </span><span style="color: blue;">#define </span><span style="color: black;">ROW_HEIGHT 100 </span><span style="color: blue;">#define </span><span style="color: black;">ROW_WIDTH ROW_HEIGHT </span><span style="color: blue;">#define </span><span style="color: black;">CELL_SPACING 10 @</span><span style="color: blue;">interface </span><span style="color: black;">KCMainViewController (){ NSMutableArray *_imageViews; } @end @implementation KCMainViewController - (</span><span style="color: blue;">void</span><span style="color: black;">)viewDidLoad { [super viewDidLoad]; [self layoutUI]; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 界面布局 -(</span><span style="color: blue;">void</span><span style="color: black;">)layoutUI{ </span><span style="color: green;">//创建多个图片控件用于显示图片 </span><span style="color: black;">_imageViews=[NSMutableArray </span><span style="color: blue;">array</span><span style="color: black;">]; </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">r=0; r<ROW_COUNT; r++) { </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">c=0; c<COLUMN_COUNT; c++) { UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(c*ROW_WIDTH+(c*CELL_SPACING), r*ROW_HEIGHT+(r*CELL_SPACING ), ROW_WIDTH, ROW_HEIGHT)]; imageView.contentMode=UIViewContentModeScaleAspectFit; </span><span style="color: green;">// imageView.backgroundColor=[UIColor redColor]; </span><span style="color: black;">[self.view addSubview:imageView]; [_imageViews addObject:imageView]; } } UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame=CGRectMake(50, 500, 220, 25); [button setTitle:@</span><span style="color: rgb(163, 21, 21);">"加载图片" </span><span style="color: black;">forState:UIControlStateNormal]; </span><span style="color: green;">//添加方法 </span><span style="color: black;">[button addTarget:self action:@selector(loadImageWithMultiThread) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 将图片显示到界面 -(</span><span style="color: blue;">void</span><span style="color: black;">)updateImage:(KCImageData *)imageData{ UIImage *image=[UIImage imageWithData:imageData.data]; UIImageView *imageView= _imageViews[imageData.index]; imageView.image=image; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 请求图片数据 -(NSData *)requestData:(</span><span style="color: blue;">int </span><span style="color: black;">)index{ </span><span style="color: green;">//对于多线程操作建议把线程操作放到@autoreleasepool中 </span><span style="color: black;">@autoreleasepool { NSURL *url=[NSURL URLWithString:@</span><span style="color: rgb(163, 21, 21);">"http://images.apple.com/iphone-6/overview/images/biggest_right_large.png"</span><span style="color: black;">]; NSData *data=[NSData dataWithContentsOfURL:url]; </span><span style="color: blue;">return </span><span style="color: black;">data; } } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 加载图片 -(</span><span style="color: blue;">void</span><span style="color: black;">)loadImage:(NSNumber *)index{ </span><span style="color: green;">// NSLog(@"%i",i); //currentThread方法可以取得当前操作线程 </span><span style="color: black;">NSLog(@</span><span style="color: rgb(163, 21, 21);">"current thread:%@"</span><span style="color: black;">,[NSThread currentThread]); </span><span style="color: blue;">int </span><span style="color: black;">i=[index integerValue]; </span><span style="color: green;">// NSLog(@"%i",i);//未必按顺序输出 </span><span style="color: black;">NSData *data= [self requestData:i]; KCImageData *imageData=[[KCImageData alloc]init]; imageData.index=i; imageData.data=data; [self performSelectorOnMainThread:@selector(updateImage:) withObject:imageData waitUntilDone:YES]; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 多线程下载图片 -(</span><span style="color: blue;">void</span><span style="color: black;">)loadImageWithMultiThread{ </span><span style="color: green;">//创建多个线程用于填充图片 </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<ROW_COUNT*COLUMN_COUNT; ++i) { </span><span style="color: green;">// [NSThread detachNewThreadSelector:@selector(loadImage:) toTarget:self withObject:[NSNumber numberWithInt:i]]; </span><span style="color: black;">NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector(loadImage:) object:[NSNumber numberWithInt:i]]; thread.name=[NSString stringWithFormat:@</span><span style="color: rgb(163, 21, 21);">"myThread%i"</span><span style="color: black;">,i];</span><span style="color: green;">//设置线程名称 </span><span style="color: black;">[thread start]; } } @end</span>
通过NSThread的currentThread可以取得当前操作的线程,其中会记录线程名称name和编号number,需要注意主线程编号永远为1。多个线程虽然按顺序启动,但是实际执行未必按照顺序加载照片(loadImage:方法未必依次创建,可以通过在loadImage:中打印索引查看),因为线程启动后仅仅处于就绪状态,实际是否执行要由CPU根据当前状态调度。
从上面的运行效果大家不难发现,图片并未按顺序加载,原因有两个:第一,每个线程的实际执行顺序并不一定按顺序执行(虽然是按顺序启动);第二,每个线程执行时实际网络状况很可能不一致。当然网络问题无法改变,只能尽可能让网速更快,但是可以改变线程的优先级,让15个线程优先执行某个线程。线程优先级范围为0~1,值越大优先级越高,每个线程的优先级默认为0.5。修改图片下载方法如下,改变最后一张图片加载的优先级,这样可以提高它被优先加载的几率,但是它也未必就第一个加载。因为首先其他线程是先启动的,其次网络状况我们没办法修改:
<span style="color: black;">-(</span><span style="color: blue;">void</span><span style="color: black;">)loadImageWithMultiThread{ NSMutableArray *threads=[NSMutableArray </span><span style="color: blue;">array</span><span style="color: black;">]; </span><span style="color: blue;">int </span><span style="color: black;">count=ROW_COUNT*COLUMN_COUNT; </span><span style="color: green;">//创建多个线程用于填充图片 </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<count; ++i) { </span><span style="color: green;">// [NSThread detachNewThreadSelector:@selector(loadImage:) toTarget:self withObject:[NSNumber numberWithInt:i]]; </span><span style="color: black;">NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector(loadImage:) object:[NSNumber numberWithInt:i]]; thread.name=[NSString stringWithFormat:@</span><span style="color: rgb(163, 21, 21);">"myThread%i"</span><span style="color: black;">,i];</span><span style="color: green;">//设置线程名称 </span><span style="color: blue;">if</span><span style="color: black;">(i==(count-1)){ thread.threadPriority=1.0; }</span><span style="color: blue;">else</span><span style="color: black;">{ thread.threadPriority=0.0; } [threads addObject:thread]; } </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<count; i++) { NSThread *thread=threads[i]; [thread start]; } }</span>
在线程操作过程中可以让某个线程休眠等待,优先执行其他线程操作,而且在这个过程中还可以修改某个线程的状态或者终止某个指定线程。为了解决上面优先加载最后一张图片的问题,不妨让其他线程先休眠一会等待最后一个线程执行。修改图片加载方法如下即可:
<span style="color: black;">-(NSData *)requestData:(</span><span style="color: blue;">int </span><span style="color: black;">)index{ </span><span style="color: green;">//对于多线程操作建议把线程操作放到@autoreleasepool中 </span><span style="color: black;">@autoreleasepool { </span><span style="color: green;">//对非最后一张图片加载线程休眠2秒 </span><span style="color: blue;">if </span><span style="color: black;">(index!=(ROW_COUNT*COLUMN_COUNT-1)) { [NSThread sleepForTimeInterval:2.0]; } NSURL *url=[NSURL URLWithString:_imageNames[index]]; NSData *data=[NSData dataWithContentsOfURL:url]; </span><span style="color: blue;">return </span><span style="color: black;">data; } }</span>在这里让其他线程休眠2秒,此时你就会看到最后一张图片总是第一个加载(除非网速特别差)。
线程状态分为isExecuting(正在执行)、isFinished(已经完成)、isCancellled(已经取消)三种。其中取消状态程序可以干预设置,只要调用线程的cancel方法即可。但是需要注意在主线程中仅仅能设置线程状态,并不能真正停止当前线程,如果要终止线程必须在线程中调用exist方法,这是一个静态方法,调用该方法可以退出当前线程。
假设在图片加载过程中点击停止按钮让没有完成的线程停止加载,可以改造程序如下:
<span style="color: green;">// // NSThread实现多线程 // MultiThread // // Created by Kenshin Cui on 14-3-22. // Copyright (c) 2014年 Kenshin Cui. All rights reserved. // </span><span style="color: blue;">#import </span><span style="color: rgb(163, 21, 21);">"KCMainViewController.h" </span><span style="color: blue;">#import </span><span style="color: rgb(163, 21, 21);">"KCImageData.h" </span><span style="color: blue;">#define </span><span style="color: black;">ROW_COUNT 5 </span><span style="color: blue;">#define </span><span style="color: black;">COLUMN_COUNT 3 </span><span style="color: blue;">#define </span><span style="color: black;">ROW_HEIGHT 100 </span><span style="color: blue;">#define </span><span style="color: black;">ROW_WIDTH ROW_HEIGHT </span><span style="color: blue;">#define </span><span style="color: black;">CELL_SPACING 10 @</span><span style="color: blue;">interface </span><span style="color: black;">KCMainViewController (){ NSMutableArray *_imageViews; NSMutableArray *_imageNames; NSMutableArray *_threads; } @end @implementation KCMainViewController - (</span><span style="color: blue;">void</span><span style="color: black;">)viewDidLoad { [super viewDidLoad]; [self layoutUI]; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 界面布局 -(</span><span style="color: blue;">void</span><span style="color: black;">)layoutUI{ </span><span style="color: green;">//创建多个图片空间用于显示图片 </span><span style="color: black;">_imageViews=[NSMutableArray </span><span style="color: blue;">array</span><span style="color: black;">]; </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">r=0; r<ROW_COUNT; r++) { </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">c=0; c<COLUMN_COUNT; c++) { UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(c*ROW_WIDTH+(c*CELL_SPACING), r*ROW_HEIGHT+(r*CELL_SPACING ), ROW_WIDTH, ROW_HEIGHT)]; imageView.contentMode=UIViewContentModeScaleAspectFit; </span><span style="color: green;">// imageView.backgroundColor=[UIColor redColor]; </span><span style="color: black;">[self.view addSubview:imageView]; [_imageViews addObject:imageView]; } } </span><span style="color: green;">//加载按钮 </span><span style="color: black;">UIButton *buttonStart=[UIButton buttonWithType:UIButtonTypeRoundedRect]; buttonStart.frame=CGRectMake(50, 500, 100, 25); [buttonStart setTitle:@</span><span style="color: rgb(163, 21, 21);">"加载图片" </span><span style="color: black;">forState:UIControlStateNormal]; [buttonStart addTarget:self action:@selector(loadImageWithMultiThread) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:buttonStart]; </span><span style="color: green;">//停止按钮 </span><span style="color: black;">UIButton *buttonStop=[UIButton buttonWithType:UIButtonTypeRoundedRect]; buttonStop.frame=CGRectMake(160, 500, 100, 25); [buttonStop setTitle:@</span><span style="color: rgb(163, 21, 21);">"停止加载" </span><span style="color: black;">forState:UIControlStateNormal]; [buttonStop addTarget:self action:@selector(stopLoadImage) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:buttonStop]; </span><span style="color: green;">//创建图片链接 </span><span style="color: black;">_imageNames=[NSMutableArray </span><span style="color: blue;">array</span><span style="color: black;">]; [_imageNames addObject:@</span><span style="color: black;"> </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<IMAGE_COUNT; i++) { [_imageNames addObject:[NSString stringWithFormat:@</span><span style="color: rgb(163, 21, 21);">"http://images.cnblogs.com/cnblogs_com/kenshincui/613474/o_%i.jpg"</span><span style="color: black;">,i]]; }</span><span style="color: black;"> } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 将图片显示到界面 -(</span><span style="color: blue;">void</span><span style="color: black;">)updateImage:(KCImageData *)imageData{ UIImage *image=[UIImage imageWithData:imageData.data]; UIImageView *imageView= _imageViews[imageData.index]; imageView.image=image; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 请求图片数据 -(NSData *)requestData:(</span><span style="color: blue;">int </span><span style="color: black;">)index{ </span><span style="color: green;">//对于多线程操作建议把线程操作放到@autoreleasepool中 </span><span style="color: black;">@autoreleasepool { NSURL *url=[NSURL URLWithString:_imageNames[index]]; NSData *data=[NSData dataWithContentsOfURL:url]; </span><span style="color: blue;">return </span><span style="color: black;">data; } } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 加载图片 -(</span><span style="color: blue;">void</span><span style="color: black;">)loadImage:(NSNumber *)index{ </span><span style="color: blue;">int </span><span style="color: black;">i=[index integerValue]; NSData *data= [self requestData:i]; NSThread *currentThread=[NSThread currentThread]; </span><span style="color: green;">// 如果当前线程处于取消状态,则退出当前线程 </span><span style="color: blue;">if </span><span style="color: black;">(currentThread.isCancelled) { NSLog(@</span><span style="color: rgb(163, 21, 21);">"thread(%@) will be cancelled!"</span><span style="color: black;">,currentThread); [NSThread exit];</span><span style="color: green;">//取消当前线程 </span><span style="color: black;">} KCImageData *imageData=[[KCImageData alloc]init]; imageData.index=i; imageData.data=data; [self performSelectorOnMainThread:@selector(updateImage:) withObject:imageData waitUntilDone:YES]; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 多线程下载图片 -(</span><span style="color: blue;">void</span><span style="color: black;">)loadImageWithMultiThread{ </span><span style="color: blue;">int </span><span style="color: black;">count=ROW_COUNT*COLUMN_COUNT; _threads=[NSMutableArray arrayWithCapacity:count]; </span><span style="color: green;">//创建多个线程用于填充图片 </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<count; ++i) { NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector(loadImage:) object:[NSNumber numberWithInt:i]]; thread.name=[NSString stringWithFormat:@</span><span style="color: rgb(163, 21, 21);">"myThread%i"</span><span style="color: black;">,i];</span><span style="color: green;">//设置线程名称 </span><span style="color: black;">[_threads addObject:thread]; } </span><span style="color: green;">//循环启动线程 </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<count; ++i) { NSThread *thread= _threads[i]; [thread start]; } } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 停止加载图片 -(</span><span style="color: blue;">void</span><span style="color: black;">)stopLoadImage{ </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<ROW_COUNT*COLUMN_COUNT; i++) { NSThread *thread= _threads[i]; </span><span style="color: green;">//判断线程是否完成,如果没有完成则设置为取消状态 //注意设置为取消状态仅仅是改变了线程状态而言,并不能终止线程 </span><span style="color: blue;">if </span><span style="color: black;">(!thread.isFinished) { [thread cancel]; } } } @end</span>
运行效果(点击加载大概1秒后点击停止加载):
使用NSThread在进行多线程开发过程中操作比较简单,但是要控制线程执行顺序并不容易(前面万不得已采用了休眠的方法),另外在这个过程中如果打印线程会发现循环几次就创建了几个线程,这在实际开发过程中是不得不考虑的问题,因为每个线程的创建也是相当占用系统开销的。
为了简化多线程开发过程,苹果官方对NSObject进行分类扩展(本质还是创建NSThread),对于简单的多线程操作可以直接使用这些扩展方法。
- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg:在后台执行一个操作,本质就是重新创建一个线程执行当前方法。
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait:在指定的线程上执行一个方法,需要用户创建一个线程对象。
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait:在主线程上执行一个方法(前面已经使用过)。
例如前面加载图多个图片的方法,可以改为后台线程执行:
<span style="color: black;">-(</span><span style="color: blue;">void</span><span style="color: black;">)loadImageWithMultiThread{ </span><span style="color: blue;">int </span><span style="color: black;">count=ROW_COUNT*COLUMN_COUNT; </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<count; ++i) { [self performSelectorInBackground:@selector(loadImage:) withObject:[NSNumber numberWithInt:i]]; } }</span>
使用NSOperation和NSOperationQueue进行多线程开发类似于C#中的线程池,只要将一个NSOperation(实际开中需要使用其子类NSInvocationOperation、NSBlockOperation)放到NSOperationQueue这个队列中线程就会依次启动。NSOperationQueue负责管理、执行所有的NSOperation,在这个过程中可以更加容易的管理线程总数和控制线程之间的依赖关系。
NSOperation有两个常用子类用于创建线程操作:NSInvocationOperation和NSBlockOperation,两种方式本质没有区别,但是是后者使用Block形式进行代码组织,使用相对方便。
首先使用NSInvocationOperation进行一张图片的加载演示,整个过程就是:创建一个操作,在这个操作中指定调用方法和参数,然后加入到操作队列。其他代码基本不用修改,直接修加载图片方法如下:
<span style="color: black;">-(</span><span style="color: blue;">void</span><span style="color: black;">)loadImageWithMultiThread{ </span><span style="color: green;">/*创建一个调用操作 object:调用方法参数 */ </span><span style="color: black;">NSInvocationOperation *invocationOperation=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(loadImage) object:nil]; </span><span style="color: green;">//创建完NSInvocationOperation对象并不会调用,它由一个start方法启动操作,但是注意如果直接调用start方法,则此操作会在主线程中调用,一般不会这么操作,而是添加到NSOperationQueue中 // [invocationOperation start]; //创建操作队列 </span><span style="color: black;">NSOperationQueue *operationQueue=[[NSOperationQueue alloc]init]; </span><span style="color: green;">//注意添加到操作队后,队列会开启一个线程执行此操作 </span><span style="color: black;">[operationQueue addOperation:invocationOperation]; }</span>
下面采用NSBlockOperation创建多个线程加载图片。
<span style="color: green;">// // NSOperation实现多线程 // MultiThread // // Created by Kenshin Cui on 14-3-22. // Copyright (c) 2014年 Kenshin Cui. All rights reserved. // </span><span style="color: blue;">#import </span><span style="color: rgb(163, 21, 21);">"KCMainViewController.h" </span><span style="color: blue;">#import </span><span style="color: rgb(163, 21, 21);">"KCImageData.h" </span><span style="color: blue;">#define </span><span style="color: black;">ROW_COUNT 5 </span><span style="color: blue;">#define </span><span style="color: black;">COLUMN_COUNT 3 </span><span style="color: blue;">#define </span><span style="color: black;">ROW_HEIGHT 100 </span><span style="color: blue;">#define </span><span style="color: black;">ROW_WIDTH ROW_HEIGHT </span><span style="color: blue;">#define </span><span style="color: black;">CELL_SPACING 10 @</span><span style="color: blue;">interface </span><span style="color: black;">KCMainViewController (){ NSMutableArray *_imageViews; NSMutableArray *_imageNames; } @end @implementation KCMainViewController - (</span><span style="color: blue;">void</span><span style="color: black;">)viewDidLoad { [super viewDidLoad]; [self layoutUI]; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 界面布局 -(</span><span style="color: blue;">void</span><span style="color: black;">)layoutUI{ </span><span style="color: green;">//创建多个图片控件用于显示图片 </span><span style="color: black;">_imageViews=[NSMutableArray </span><span style="color: blue;">array</span><span style="color: black;">]; </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">r=0; r<ROW_COUNT; r++) { </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">c=0; c<COLUMN_COUNT; c++) { UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(c*ROW_WIDTH+(c*CELL_SPACING), r*ROW_HEIGHT+(r*CELL_SPACING ), ROW_WIDTH, ROW_HEIGHT)]; imageView.contentMode=UIViewContentModeScaleAspectFit; </span><span style="color: green;">// imageView.backgroundColor=[UIColor redColor]; </span><span style="color: black;">[self.view addSubview:imageView]; [_imageViews addObject:imageView]; } } UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame=CGRectMake(50, 500, 220, 25); [button setTitle:@</span><span style="color: rgb(163, 21, 21);">"加载图片" </span><span style="color: black;">forState:UIControlStateNormal]; </span><span style="color: green;">//添加方法 </span><span style="color: black;">[button addTarget:self action:@selector(loadImageWithMultiThread) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; </span><span style="color: green;">//创建图片链接 </span><span style="color: black;">_imageNames=[NSMutableArray </span><span style="color: blue;">array</span><span style="color: black;">]; </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<IMAGE_COUNT; i++) { [_imageNames addObject:[NSString stringWithFormat:@</span><span style="color: rgb(163, 21, 21);">"http://images.cnblogs.com/cnblogs_com/kenshincui/613474/o_%i.jpg"</span><span style="color: black;">,i]]; }</span><span style="color: black;"> } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 将图片显示到界面 -(</span><span style="color: blue;">void</span><span style="color: black;">)updateImageWithData:(NSData *)data andIndex:(</span><span style="color: blue;">int </span><span style="color: black;">)index{ UIImage *image=[UIImage imageWithData:data]; UIImageView *imageView= _imageViews[index]; imageView.image=image; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 请求图片数据 -(NSData *)requestData:(</span><span style="color: blue;">int </span><span style="color: black;">)index{ </span><span style="color: green;">//对于多线程操作建议把线程操作放到@autoreleasepool中 </span><span style="color: black;">@autoreleasepool { NSURL *url=[NSURL URLWithString:_imageNames[index]]; NSData *data=[NSData dataWithContentsOfURL:url]; </span><span style="color: blue;">return </span><span style="color: black;">data; } } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 加载图片 -(</span><span style="color: blue;">void</span><span style="color: black;">)loadImage:(NSNumber *)index{ </span><span style="color: blue;">int </span><span style="color: black;">i=[index integerValue]; </span><span style="color: green;">//请求数据 </span><span style="color: black;">NSData *data= [self requestData:i]; NSLog(@</span><span style="color: rgb(163, 21, 21);">"%@"</span><span style="color: black;">,[NSThread currentThread]); </span><span style="color: green;">//更新UI界面,此处调用了主线程队列的方法(mainQueue是UI主线程) </span><span style="color: black;">[[NSOperationQueue mainQueue] addOperationWithBlock:^{ [self updateImageWithData:data andIndex:i]; }]; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 多线程下载图片 -(</span><span style="color: blue;">void</span><span style="color: black;">)loadImageWithMultiThread{ </span><span style="color: blue;">int </span><span style="color: black;">count=ROW_COUNT*COLUMN_COUNT; </span><span style="color: green;">//创建操作队列 </span><span style="color: black;">NSOperationQueue *operationQueue=[[NSOperationQueue alloc]init]; operationQueue.maxConcurrentOperationCount=5;</span><span style="color: green;">//设置最大并发线程数 //创建多个线程用于填充图片 </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<count; ++i) { </span><span style="color: green;">//方法1:创建操作块添加到队列 // //创建多线程操作 // NSBlockOperation *blockOperation=[NSBlockOperation blockOperationWithBlock:^{ // [self loadImage:[NSNumber numberWithInt:i]]; // }]; // //创建操作队列 // // [operationQueue addOperation:blockOperation]; //方法2:直接使用操队列添加操作 </span><span style="color: black;">[operationQueue addOperationWithBlock:^{ [self loadImage:[NSNumber numberWithInt:i]]; }]; } } @end</span>
对比之前NSThread加载张图片很发现核心代码简化了不少,这里着重强调两点:
前面使用NSThread很难控制线程的执行顺序,但是使用NSOperation就容易多了,每个NSOperation可以设置依赖线程。假设操作A依赖于操作B,线程操作队列在启动线程时就会首先执行B操作,然后执行A。对于前面优先加载最后一张图的需求,只要设置前面的线程操作的依赖线程为最后一个操作即可。修改图片加载方法如下:
<span style="color: black;">-(</span><span style="color: blue;">void</span><span style="color: black;">)loadImageWithMultiThread{ </span><span style="color: blue;">int </span><span style="color: black;">count=ROW_COUNT*COLUMN_COUNT; </span><span style="color: green;">//创建操作队列 </span><span style="color: black;">NSOperationQueue *operationQueue=[[NSOperationQueue alloc]init]; operationQueue.maxConcurrentOperationCount=5;</span><span style="color: green;">//设置最大并发线程数 </span><span style="color: black;">NSBlockOperation *lastBlockOperation=[NSBlockOperation blockOperationWithBlock:^{ [self loadImage:[NSNumber numberWithInt:(count-1)]]; }]; </span><span style="color: green;">//创建多个线程用于填充图片 </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<count-1; ++i) { </span><span style="color: green;">//方法1:创建操作块添加到队列 //创建多线程操作 </span><span style="color: black;">NSBlockOperation *blockOperation=[NSBlockOperation blockOperationWithBlock:^{ [self loadImage:[NSNumber numberWithInt:i]]; }]; </span><span style="color: green;">//设置依赖操作为最后一张图片加载操作 </span><span style="color: black;">[blockOperation addDependency:lastBlockOperation]; [operationQueue addOperation:blockOperation]; } </span><span style="color: green;">//将最后一个图片的加载操作加入线程队列 </span><span style="color: black;">[operationQueue addOperation:lastBlockOperation]; }</span>
运行效果:
可以看到虽然加载最后一张图片的操作最后被加入到操作队列,但是它却是被第一个执行的。操作依赖关系可以设置多个,例如A依赖于B、B依赖于C…但是千万不要设置为循环依赖关系(例如A依赖于B,B依赖于C,C又依赖于A),否则是不会被执行的。
GCD(Grand Central Dispatch)是基于C语言开发的一套多线程开发机制,也是目前苹果官方推荐的多线程开发方法。前面也说过三种开发中GCD抽象层次最高,当然是用起来也最简单,只是它基于C语言开发,并不像NSOperation是面向对象的开发,而是完全面向过程的。对于熟悉C#异步调用的朋友对于GCD学习起来应该很快,因为它与C#中的异步调用基本是一样的。这种机制相比较于前面两种多线程开发方式最显著的优点就是它对于多核运算更加有效。
GCD中也有一个类似于NSOperationQueue的队列,GCD统一管理整个队列中的任务。但是GCD中的队列分为并行队列和串行队列两类:
其实在GCD中还有一个特殊队列就是主队列,用来执行主线程上的操作任务(从前面的演示中可以看到其实在NSOperation中也有一个主队列)。
使用串行队列时首先要创建一个串行队列,然后调用异步调用方法,在此方法中传入串行队列和线程操作即可自动执行。下面使用线程队列演示图片的加载过程,你会发现多张图片会按顺序加载,因为当前队列中只有一个线程。
<span style="color: green;">// // GCD实现多线程 // MultiThread // // Created by Kenshin Cui on 14-3-22. // Copyright (c) 2014年 Kenshin Cui. All rights reserved. // </span><span style="color: blue;">#import </span><span style="color: rgb(163, 21, 21);">"KCMainViewController.h" </span><span style="color: blue;">#import </span><span style="color: rgb(163, 21, 21);">"KCImageData.h" </span><span style="color: blue;">#define </span><span style="color: black;">ROW_COUNT 5 </span><span style="color: blue;">#define </span><span style="color: black;">COLUMN_COUNT 3 </span><span style="color: blue;">#define </span><span style="color: black;">ROW_HEIGHT 100 </span><span style="color: blue;">#define </span><span style="color: black;">ROW_WIDTH ROW_HEIGHT </span><span style="color: blue;">#define </span><span style="color: black;">CELL_SPACING 10 @</span><span style="color: blue;">interface </span><span style="color: black;">KCMainViewController (){ NSMutableArray *_imageViews; NSMutableArray *_imageNames; } @end @implementation KCMainViewController - (</span><span style="color: blue;">void</span><span style="color: black;">)viewDidLoad { [super viewDidLoad]; [self layoutUI]; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 界面布局 -(</span><span style="color: blue;">void</span><span style="color: black;">)layoutUI{ </span><span style="color: green;">//创建多个图片控件用于显示图片 </span><span style="color: black;">_imageViews=[NSMutableArray </span><span style="color: blue;">array</span><span style="color: black;">]; </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">r=0; r<ROW_COUNT; r++) { </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">c=0; c<COLUMN_COUNT; c++) { UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(c*ROW_WIDTH+(c*CELL_SPACING), r*ROW_HEIGHT+(r*CELL_SPACING ), ROW_WIDTH, ROW_HEIGHT)]; imageView.contentMode=UIViewContentModeScaleAspectFit; </span><span style="color: green;">// imageView.backgroundColor=[UIColor redColor]; </span><span style="color: black;">[self.view addSubview:imageView]; [_imageViews addObject:imageView]; } } UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame=CGRectMake(50, 500, 220, 25); [button setTitle:@</span><span style="color: rgb(163, 21, 21);">"加载图片" </span><span style="color: black;">forState:UIControlStateNormal]; </span><span style="color: green;">//添加方法 </span><span style="color: black;">[button addTarget:self action:@selector(loadImageWithMultiThread) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; </span><span style="color: green;">//创建图片链接 </span><span style="color: black;">_imageNames=[NSMutableArray </span><span style="color: blue;">array</span><span style="color: black;">]; </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<ROW_COUNT*COLUMN_COUNT; i++) { [_imageNames addObject:[NSString stringWithFormat:@</span><span style="color: rgb(163, 21, 21);">"http://images.cnblogs.com/cnblogs_com/kenshincui/613474/o_%i.jpg"</span><span style="color: black;">,i]]; } } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 将图片显示到界面 -(</span><span style="color: blue;">void</span><span style="color: black;">)updateImageWithData:(NSData *)data andIndex:(</span><span style="color: blue;">int </span><span style="color: black;">)index{ UIImage *image=[UIImage imageWithData:data]; UIImageView *imageView= _imageViews[index]; imageView.image=image; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 请求图片数据 -(NSData *)requestData:(</span><span style="color: blue;">int </span><span style="color: black;">)index{ NSURL *url=[NSURL URLWithString:_imageNames[index]]; NSData *data=[NSData dataWithContentsOfURL:url]; </span><span style="color: blue;">return </span><span style="color: black;">data; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 加载图片 -(</span><span style="color: blue;">void</span><span style="color: black;">)loadImage:(NSNumber *)index{ </span><span style="color: green;">//如果在串行队列中会发现当前线程打印变化完全一样,因为他们在一个线程中 </span><span style="color: black;">NSLog(@</span><span style="color: rgb(163, 21, 21);">"thread is :%@"</span><span style="color: black;">,[NSThread currentThread]); </span><span style="color: blue;">int </span><span style="color: black;">i=[index integerValue]; </span><span style="color: green;">//请求数据 </span><span style="color: black;">NSData *data= [self requestData:i]; </span><span style="color: green;">//更新UI界面,此处调用了GCD主线程队列的方法 </span><span style="color: black;">dispatch_queue_t mainQueue= dispatch_get_main_queue(); dispatch_sync(mainQueue, ^{ [self updateImageWithData:data andIndex:i]; }); } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 多线程下载图片 -(</span><span style="color: blue;">void</span><span style="color: black;">)loadImageWithMultiThread{ </span><span style="color: blue;">int </span><span style="color: black;">count=ROW_COUNT*COLUMN_COUNT; </span><span style="color: green;">/*创建一个串行队列 第一个参数:队列名称 第二个参数:队列类型 */ </span><span style="color: black;">dispatch_queue_t serialQueue=dispatch_queue_create(</span><span style="color: rgb(163, 21, 21);">"myThreadQueue1"</span><span style="color: black;">, DISPATCH_QUEUE_SERIAL);</span><span style="color: green;">//注意queue对象不是指针类型 //创建多个线程用于填充图片 </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<count; ++i) { </span><span style="color: green;">//异步执行队列任务 </span><span style="color: black;">dispatch_async(serialQueue, ^{ [self loadImage:[NSNumber numberWithInt:i]]; }); } </span><span style="color: green;">//非ARC环境请释放 // dispatch_release(seriQueue); </span><span style="color: black;">} @end</span>
运行效果:
在上面的代码中更新UI还使用了GCD方法的主线程队列dispatch_get_main_queue(),其实这与前面两种主线程更新UI没有本质的区别。
并发队列同样是使用dispatch_queue_create()方法创建,只是最后一个参数指定为DISPATCH_QUEUE_CONCURRENT进行创建,但是在实际开发中我们通常不会重新创建一个并发队列而是使用dispatch_get_global_queue()方法取得一个全局的并发队列(当然如果有多个并发队列可以使用前者创建)。下面通过并行队列演示一下多个图片的加载。代码与上面串行队列加载类似,只需要修改照片加载方法如下:
<span style="color: black;">-(</span><span style="color: blue;">void</span><span style="color: black;">)loadImageWithMultiThread{ </span><span style="color: blue;">int </span><span style="color: black;">count=ROW_COUNT*COLUMN_COUNT; </span><span style="color: green;">/*取得全局队列 第一个参数:线程优先级 第二个参数:标记参数,目前没有用,一般传入0 */ </span><span style="color: black;">dispatch_queue_t globalQueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); </span><span style="color: green;">//创建多个线程用于填充图片 </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<count; ++i) { </span><span style="color: green;">//异步执行队列任务 </span><span style="color: black;">dispatch_async(globalQueue, ^{ [self loadImage:[NSNumber numberWithInt:i]]; }); } }</span>
运行效果:
细心的朋友肯定会思考,既然可以使用dispatch_async()异步调用方法,是不是还有同步方法,确实如此,在GCD中还有一个dispatch_sync()方法。假设将上面的代码修改为同步调用,可以看到如下效果:
可以看点击按钮后按钮无法再次点击,因为所有图片的加载全部在主线程中(可以打印线程查看),主线程被阻塞,造成图片最终是一次性显示。可以得出结论:
GCD执行任务的方法并非只有简单的同步调用方法和异步调用方法,还有其他一些常用方法:
说到多线程就不得不提多线程中的锁机制,多线程操作过程中往往多个线程是并发执行的,同一个资源可能被多个线程同时访问,造成资源抢夺,这个过程中如果没有锁机制往往会造成重大问题。举例来说,每年春节都是一票难求,在12306买票的过程中,成百上千的票瞬间就消失了。不妨假设某辆车有1千张票,同时有几万人在抢这列车的车票,顺利的话前面的人都能买到票。但是如果现在只剩下一张票了,而同时还有几千人在购买这张票,虽然在进入购票环节的时候会判断当前票数,但是当前已经有100个线程进入购票的环节,每个线程处理完票数都会减1,100个线程执行完当前票数为-99,遇到这种情况很明显是不允许的。
要解决资源抢夺问题在iOS中有常用的有两种方法:一种是使用NSLock同步锁,另一种是使用@synchronized代码块。两种方法实现原理是类似的,只是在处理上代码块使用起来更加简单(C#中也有类似的处理机制synchronized和lock)。
这里不妨还拿图片加载来举例,假设现在有9张图片,但是有15个线程都准备加载这9张图片,约定不能重复加载同一张图片,这样就形成了一个资源抢夺的情况。在下面的程序中将创建9张图片,每次读取照片链接时首先判断当前链接数是否大于1,用完一个则立即移除,最多只有9个。在使用同步方法之前先来看一下错误的写法:
<span style="color: green;">// // 线程同步 // MultiThread // // Created by Kenshin Cui on 14-3-22. // Copyright (c) 2014年 Kenshin Cui. All rights reserved. // </span><span style="color: blue;">#import </span><span style="color: rgb(163, 21, 21);">"KCMainViewController.h" </span><span style="color: blue;">#import </span><span style="color: rgb(163, 21, 21);">"KCImageData.h" </span><span style="color: blue;">#define </span><span style="color: black;">ROW_COUNT 5 </span><span style="color: blue;">#define </span><span style="color: black;">COLUMN_COUNT 3 </span><span style="color: blue;">#define </span><span style="color: black;">ROW_HEIGHT 100 </span><span style="color: blue;">#define </span><span style="color: black;">ROW_WIDTH ROW_HEIGHT </span><span style="color: blue;">#define </span><span style="color: black;">CELL_SPACING 10 </span><span style="color: blue;">#define </span><span style="color: black;">IMAGE_COUNT 9 @</span><span style="color: blue;">interface </span><span style="color: black;">KCMainViewController (){ NSMutableArray *_imageViews; NSMutableArray *_imageNames; } @end @implementation KCMainViewController - (</span><span style="color: blue;">void</span><span style="color: black;">)viewDidLoad { [super viewDidLoad]; [self layoutUI]; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 界面布局 -(</span><span style="color: blue;">void</span><span style="color: black;">)layoutUI{ </span><span style="color: green;">//创建多个图片控件用于显示图片 </span><span style="color: black;">_imageViews=[NSMutableArray </span><span style="color: blue;">array</span><span style="color: black;">]; </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">r=0; r<ROW_COUNT; r++) { </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">c=0; c<COLUMN_COUNT; c++) { UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(c*ROW_WIDTH+(c*CELL_SPACING), r*ROW_HEIGHT+(r*CELL_SPACING ), ROW_WIDTH, ROW_HEIGHT)]; imageView.contentMode=UIViewContentModeScaleAspectFit; </span><span style="color: green;">// imageView.backgroundColor=[UIColor redColor]; </span><span style="color: black;">[self.view addSubview:imageView]; [_imageViews addObject:imageView]; } } UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame=CGRectMake(50, 500, 220, 25); [button setTitle:@</span><span style="color: rgb(163, 21, 21);">"加载图片" </span><span style="color: black;">forState:UIControlStateNormal]; </span><span style="color: green;">//添加方法 </span><span style="color: black;">[button addTarget:self action:@selector(loadImageWithMultiThread) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; </span><span style="color: green;">//创建图片链接 </span><span style="color: black;">_imageNames=[NSMutableArray </span><span style="color: blue;">array</span><span style="color: black;">]; </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<IMAGE_COUNT; i++) { [_imageNames addObject:[NSString stringWithFormat:@</span><span style="color: rgb(163, 21, 21);">"http://images.cnblogs.com/cnblogs_com/kenshincui/613474/o_%i.jpg"</span><span style="color: black;">,i]]; } } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 将图片显示到界面 -(</span><span style="color: blue;">void</span><span style="color: black;">)updateImageWithData:(NSData *)data andIndex:(</span><span style="color: blue;">int </span><span style="color: black;">)index{ UIImage *image=[UIImage imageWithData:data]; UIImageView *imageView= _imageViews[index]; imageView.image=image; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 请求图片数据 -(NSData *)requestData:(</span><span style="color: blue;">int </span><span style="color: black;">)index{ NSData *data; NSString *name; </span><span style="color: blue;">if </span><span style="color: black;">(_imageNames.count>0) { name=[_imageNames lastObject]; [_imageNames removeObject:name]; } </span><span style="color: blue;">if</span><span style="color: black;">(name){ NSURL *url=[NSURL URLWithString:name]; data=[NSData dataWithContentsOfURL:url]; } </span><span style="color: blue;">return </span><span style="color: black;">data; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 加载图片 -(</span><span style="color: blue;">void</span><span style="color: black;">)loadImage:(NSNumber *)index{ </span><span style="color: blue;">int </span><span style="color: black;">i=[index integerValue]; </span><span style="color: green;">//请求数据 </span><span style="color: black;">NSData *data= [self requestData:i]; </span><span style="color: green;">//更新UI界面,此处调用了GCD主线程队列的方法 </span><span style="color: black;">dispatch_queue_t mainQueue= dispatch_get_main_queue(); dispatch_sync(mainQueue, ^{ [self updateImageWithData:data andIndex:i]; }); } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 多线程下载图片 -(</span><span style="color: blue;">void</span><span style="color: black;">)loadImageWithMultiThread{ </span><span style="color: blue;">int </span><span style="color: black;">count=ROW_COUNT*COLUMN_COUNT; dispatch_queue_t globalQueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); </span><span style="color: green;">//创建多个线程用于填充图片 </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<count; ++i) { </span><span style="color: green;">//异步执行队列任务 </span><span style="color: black;">dispatch_async(globalQueue, ^{ [self loadImage:[NSNumber numberWithInt:i]]; }); } } @end</span>
首先在_imageNames中存储了9个链接用于下载图片,然后在requestData:方法中每次只需先判断_imageNames的个数,如果大于一就读取一个链接加载图片,随即把用过的链接删除,一切貌似都没有问题。此时运行程序:
上面这个结果不一定每次都出现,关键要看从_imageNames读取链接、删除链接的速度,如果足够快可能不会有任何问题,但是如果速度稍慢就会出现上面的情况,很明显上面情况并不满足前面的需求。
分析这个问题造成的原因主:当一个线程A已经开始获取图片链接,获取完之后还没有来得及从_imageNames中删除,另一个线程B已经进入相应代码中,由于每次读取的都是_imageNames的最后一个元素,因此后面的线程其实和前面线程取得的是同一个图片链接这样就造成图中看到的情况。要解决这个问题,只要保证线程A进入相应代码之后B无法进入,只有等待A完成相关操作之后B才能进入即可。下面分别使用NSLock和@synchronized对代码进行修改。
iOS中对于资源抢占的问题可以使用同步锁NSLock来解决,使用时把需要加锁的代码(以后暂时称这段代码为”加锁代码“)放到NSLock的lock和unlock之间,一个线程A进入加锁代码之后由于已经加锁,另一个线程B就无法访问,只有等待前一个线程A执行完加锁代码后解锁,B线程才能访问加锁代码。需要注意的是lock和unlock之间的”加锁代码“应该是抢占资源的读取和修改代码,不要将过多的其他操作代码放到里面,否则一个线程执行的时候另一个线程就一直在等待,就无法发挥多线程的作用了。
另外,在上面的代码中”抢占资源“_imageNames定义成了成员变量,这么做是不明智的,应该定义为“原子属性”。对于被抢占资源来说将其定义为原子属性是一个很好的习惯,因为有时候很难保证同一个资源不在别处读取和修改。nonatomic属性读取的是内存数据(寄存器计算好的结果),而atomic就保证直接读取寄存器的数据,这样一来就不会出现一个线程正在修改数据,而另一个线程读取了修改之前(存储在内存中)的数据,永远保证同时只有一个线程在访问一个属性。
下面的代码演示了如何使用NSLock进行线程同步:
KCMainViewController.h
<span style="color: green;">// // KCMainViewController.h // MultiThread // // Created by Kenshin Cui on 14-3-22. // Copyright (c) 2014年 Kenshin Cui. All rights reserved. // </span><span style="color: blue;">#import </span><span style="color: rgb(163, 21, 21);"><UIKit/UIKit.h> </span><span style="color: black;">@</span><span style="color: blue;">interface </span><span style="color: black;">KCMainViewController : UIViewController @</span><span style="color: blue;">property </span><span style="color: black;">(atomic,strong) NSMutableArray *imageNames; @end</span>
KCMainViewController.m
<span style="color: green;">// // 线程同步 // MultiThread // // Created by Kenshin Cui on 14-3-22. // Copyright (c) 2014年 Kenshin Cui. All rights reserved. // </span><span style="color: blue;">#import </span><span style="color: rgb(163, 21, 21);">"KCMainViewController.h" </span><span style="color: blue;">#import </span><span style="color: rgb(163, 21, 21);">"KCImageData.h" </span><span style="color: blue;">#define </span><span style="color: black;">ROW_COUNT 5 </span><span style="color: blue;">#define </span><span style="color: black;">COLUMN_COUNT 3 </span><span style="color: blue;">#define </span><span style="color: black;">ROW_HEIGHT 100 </span><span style="color: blue;">#define </span><span style="color: black;">ROW_WIDTH ROW_HEIGHT </span><span style="color: blue;">#define </span><span style="color: black;">CELL_SPACING 10 </span><span style="color: blue;">#define </span><span style="color: black;">IMAGE_COUNT 9 @</span><span style="color: blue;">interface </span><span style="color: black;">KCMainViewController (){ NSMutableArray *_imageViews; NSLock *_lock; } @end @implementation KCMainViewController - (</span><span style="color: blue;">void</span><span style="color: black;">)viewDidLoad { [super viewDidLoad]; [self layoutUI]; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 界面布局 -(</span><span style="color: blue;">void</span><span style="color: black;">)layoutUI{ </span><span style="color: green;">//创建多个图片控件用于显示图片 </span><span style="color: black;">_imageViews=[NSMutableArray </span><span style="color: blue;">array</span><span style="color: black;">]; </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">r=0; r<ROW_COUNT; r++) { </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">c=0; c<COLUMN_COUNT; c++) { UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(c*ROW_WIDTH+(c*CELL_SPACING), r*ROW_HEIGHT+(r*CELL_SPACING ), ROW_WIDTH, ROW_HEIGHT)]; imageView.contentMode=UIViewContentModeScaleAspectFit; [self.view addSubview:imageView]; [_imageViews addObject:imageView]; } } UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame=CGRectMake(50, 500, 220, 25); [button setTitle:@</span><span style="color: rgb(163, 21, 21);">"加载图片" </span><span style="color: black;">forState:UIControlStateNormal]; </span><span style="color: green;">//添加方法 </span><span style="color: black;">[button addTarget:self action:@selector(loadImageWithMultiThread) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; </span><span style="color: green;">//创建图片链接 </span><span style="color: black;">_imageNames=[NSMutableArray </span><span style="color: blue;">array</span><span style="color: black;">]; </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<IMAGE_COUNT; i++) { [_imageNames addObject:[NSString stringWithFormat:@</span><span style="color: rgb(163, 21, 21);">"http://images.cnblogs.com/cnblogs_com/kenshincui/613474/o_%i.jpg"</span><span style="color: black;">,i]]; } </span><span style="color: green;">//初始化锁对象 </span><span style="color: black;">_lock=[[NSLock alloc]init]; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 将图片显示到界面 -(</span><span style="color: blue;">void</span><span style="color: black;">)updateImageWithData:(NSData *)data andIndex:(</span><span style="color: blue;">int </span><span style="color: black;">)index{ UIImage *image=[UIImage imageWithData:data]; UIImageView *imageView= _imageViews[index]; imageView.image=image; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 请求图片数据 -(NSData *)requestData:(</span><span style="color: blue;">int </span><span style="color: black;">)index{ NSData *data; NSString *name; </span><span style="color: green;">//加锁 </span><span style="color: black;">[_lock lock]; </span><span style="color: blue;">if </span><span style="color: black;">(_imageNames.count>0) { name=[_imageNames lastObject]; [_imageNames removeObject:name]; } </span><span style="color: green;">//使用完解锁 </span><span style="color: black;">[_lock unlock]; </span><span style="color: blue;">if</span><span style="color: black;">(name){ NSURL *url=[NSURL URLWithString:name]; data=[NSData dataWithContentsOfURL:url]; } </span><span style="color: blue;">return </span><span style="color: black;">data; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 加载图片 -(</span><span style="color: blue;">void</span><span style="color: black;">)loadImage:(NSNumber *)index{ </span><span style="color: blue;">int </span><span style="color: black;">i=[index integerValue]; </span><span style="color: green;">//请求数据 </span><span style="color: black;">NSData *data= [self requestData:i]; </span><span style="color: green;">//更新UI界面,此处调用了GCD主线程队列的方法 </span><span style="color: black;">dispatch_queue_t mainQueue= dispatch_get_main_queue(); dispatch_sync(mainQueue, ^{ [self updateImageWithData:data andIndex:i]; }); } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 多线程下载图片 -(</span><span style="color: blue;">void</span><span style="color: black;">)loadImageWithMultiThread{ </span><span style="color: blue;">int </span><span style="color: black;">count=ROW_COUNT*COLUMN_COUNT; dispatch_queue_t globalQueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); </span><span style="color: green;">//创建多个线程用于填充图片 </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<count; ++i) { </span><span style="color: green;">//异步执行队列任务 </span><span style="color: black;">dispatch_async(globalQueue, ^{ [self loadImage:[NSNumber numberWithInt:i]]; }); } } @end</span>
运行效果:
前面也说过使用同步锁时如果一个线程A已经加锁,线程B就无法进入。那么B怎么知道是否资源已经被其他线程锁住呢?可以通过tryLock方法,此方法会返回一个BOOL型的值,如果为YES说明获取锁成功,否则失败。另外还有一个lockBeforeData:方法指定在某个时间内获取锁,同样返回一个BOOL值,如果在这个时间内加锁成功则返回YES,失败则返回NO。
使用@synchronized解决线程同步问题相比较NSLock要简单一些,日常开发中也更推荐使用此方法。首先选择一个对象作为同步对象(一般使用self),然后将”加锁代码”(争夺资源的读取、修改代码)放到代码块中。@synchronized中的代码执行时先检查同步对象是否被另一个线程占用,如果占用该线程就会处于等待状态,直到同步对象被释放。下面的代码演示了如何使用@synchronized进行线程同步:
<span style="color: black;">-(NSData *)requestData:(</span><span style="color: blue;">int </span><span style="color: black;">)index{ NSData *data; NSString *name; </span><span style="color: green;">//线程同步 </span><span style="color: black;">@synchronized(self){ </span><span style="color: blue;">if </span><span style="color: black;">(_imageNames.count>0) { name=[_imageNames lastObject]; [NSThread sleepForTimeInterval:0.001f]; [_imageNames removeObject:name]; } } </span><span style="color: blue;">if</span><span style="color: black;">(name){ NSURL *url=[NSURL URLWithString:name]; data=[NSData dataWithContentsOfURL:url]; } </span><span style="color: blue;">return </span><span style="color: black;">data; }</span>
在GCD中提供了一种信号机制,也可以解决资源抢占问题(和同步锁的机制并不一样)。GCD中信号量是dispatch_semaphore_t类型,支持信号通知和信号等待。每当发送一个信号通知,则信号量+1;每当发送一个等待信号时信号量-1,;如果信号量为0则信号会处于等待状态,直到信号量大于0开始执行。根据这个原理我们可以初始化一个信号量变量,默认信号量设置为1,每当有线程进入“加锁代码”之后就调用信号等待命令(此时信号量为0)开始等待,此时其他线程无法进入,执行完后发送信号通知(此时信号量为1),其他线程开始进入执行,如此一来就达到了线程同步目的。
<span style="color: green;">// // GCD实现多线程--消息信号 // MultiThread // // Created by Kenshin Cui on 14-3-22. // Copyright (c) 2014年 Kenshin Cui. All rights reserved. // </span><span style="color: blue;">#import </span><span style="color: rgb(163, 21, 21);">"KCMainViewController.h" </span><span style="color: blue;">#import </span><span style="color: rgb(163, 21, 21);">"KCImageData.h" </span><span style="color: blue;">#define </span><span style="color: black;">ROW_COUNT 5 </span><span style="color: blue;">#define </span><span style="color: black;">COLUMN_COUNT 3 </span><span style="color: blue;">#define </span><span style="color: black;">ROW_HEIGHT 100 </span><span style="color: blue;">#define </span><span style="color: black;">ROW_WIDTH ROW_HEIGHT </span><span style="color: blue;">#define </span><span style="color: black;">CELL_SPACING 10 </span><span style="color: blue;">#define </span><span style="color: black;">IMAGE_COUNT 9 @</span><span style="color: blue;">interface </span><span style="color: black;">KCMainViewController (){ NSMutableArray *_imageViews; NSLock *_lock; dispatch_semaphore_t _semaphore;</span><span style="color: green;">//定义一个信号量 </span><span style="color: black;">} @end @implementation KCMainViewController - (</span><span style="color: blue;">void</span><span style="color: black;">)viewDidLoad { [super viewDidLoad]; [self layoutUI]; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 界面布局 -(</span><span style="color: blue;">void</span><span style="color: black;">)layoutUI{ </span><span style="color: green;">//创建多个图片控件用于显示图片 </span><span style="color: black;">_imageViews=[NSMutableArray </span><span style="color: blue;">array</span><span style="color: black;">]; </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">r=0; r<ROW_COUNT; r++) { </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">c=0; c<COLUMN_COUNT; c++) { UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(c*ROW_WIDTH+(c*CELL_SPACING), r*ROW_HEIGHT+(r*CELL_SPACING ), ROW_WIDTH, ROW_HEIGHT)]; imageView.contentMode=UIViewContentModeScaleAspectFit; [self.view addSubview:imageView]; [_imageViews addObject:imageView]; } } UIButton *button=[UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame=CGRectMake(50, 500, 220, 25); [button setTitle:@</span><span style="color: rgb(163, 21, 21);">"加载图片" </span><span style="color: black;">forState:UIControlStateNormal]; </span><span style="color: green;">//添加方法 </span><span style="color: black;">[button addTarget:self action:@selector(loadImageWithMultiThread) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; </span><span style="color: green;">//创建图片链接 </span><span style="color: black;">_imageNames=[NSMutableArray </span><span style="color: blue;">array</span><span style="color: black;">]; </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<IMAGE_COUNT; i++) { [_imageNames addObject:[NSString stringWithFormat:@</span><span style="color: rgb(163, 21, 21);">"http://images.cnblogs.com/cnblogs_com/kenshincui/613474/o_%i.jpg"</span><span style="color: black;">,i]]; } </span><span style="color: green;">/*初始化信号量 参数是信号量初始值 */ </span><span style="color: black;">_semaphore=dispatch_semaphore_create(1); } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 将图片显示到界面 -(</span><span style="color: blue;">void</span><span style="color: black;">)updateImageWithData:(NSData *)data andIndex:(</span><span style="color: blue;">int </span><span style="color: black;">)index{ UIImage *image=[UIImage imageWithData:data]; UIImageView *imageView= _imageViews[index]; imageView.image=image; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 请求图片数据 -(NSData *)requestData:(</span><span style="color: blue;">int </span><span style="color: black;">)index{ NSData *data; NSString *name; </span><span style="color: green;">/*信号等待 第二个参数:等待时间 */ </span><span style="color: black;">dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER); </span><span style="color: blue;">if </span><span style="color: black;">(_imageNames.count>0) { name=[_imageNames lastObject]; [_imageNames removeObject:name]; } </span><span style="color: green;">//信号通知 </span><span style="color: black;">dispatch_semaphore_signal(_semaphore); </span><span style="color: blue;">if</span><span style="color: black;">(name){ NSURL *url=[NSURL URLWithString:name]; data=[NSData dataWithContentsOfURL:url]; } </span><span style="color: blue;">return </span><span style="color: black;">data; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 加载图片 -(</span><span style="color: blue;">void</span><span style="color: black;">)loadImage:(NSNumber *)index{ </span><span style="color: blue;">int </span><span style="color: black;">i=[index integerValue]; </span><span style="color: green;">//请求数据 </span><span style="color: black;">NSData *data= [self requestData:i]; </span><span style="color: green;">//更新UI界面,此处调用了GCD主线程队列的方法 </span><span style="color: black;">dispatch_queue_t mainQueue= dispatch_get_main_queue(); dispatch_sync(mainQueue, ^{ [self updateImageWithData:data andIndex:i]; }); } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 多线程下载图片 -(</span><span style="color: blue;">void</span><span style="color: black;">)loadImageWithMultiThread{ </span><span style="color: blue;">int </span><span style="color: black;">count=ROW_COUNT*COLUMN_COUNT; </span><span style="color: green;">// dispatch_queue_t globalQueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); //这里创建一个并发队列(使用全局并发队列也可以) </span><span style="color: black;">dispatch_queue_t queue=dispatch_queue_create(</span><span style="color: rgb(163, 21, 21);">"myQueue"</span><span style="color: black;">, DISPATCH_QUEUE_CONCURRENT); </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<count; i++) { dispatch_async(queue, ^{ [self loadImage:[NSNumber numberWithInt:i]]; }); } } @end</span>
运行效果与前面使用同步锁是一样的。
由于线程的调度是透明的,程序有时候很难对它进行有效的控制,为了解决这个问题iOS提供了NSCondition来控制线程通信(同前面GCD的信号机制类似)。NSCondition实现了NSLocking协议,所以它本身也有lock和unlock方法,因此也可以将它作为NSLock解决线程同步问题,此时使用方法跟NSLock没有区别,只要在线程开始时加锁,取得资源后释放锁即可,这部分内容比较简单在此不再演示。当然,单纯解决线程同步问题不是NSCondition设计的主要目的,NSCondition更重要的是解决线程之间的调度关系(当然,这个过程中也必须先加锁、解锁)。NSCondition可以调用wati方法控制某个线程处于等待状态,直到其他线程调用signal(此方法唤醒一个线程,如果有多个线程在等待则任意唤醒一个)或者broadcast(此方法会唤醒所有等待线程)方法唤醒该线程才能继续。
假设当前imageNames没有任何图片,而整个界面能够加载15张图片(每张都不能重复),现在创建15个线程分别从imageNames中取图片加载到界面中。由于imageNames中没有任何图片,那么15个线程都处于等待状态,只有当调用图片创建方法往imageNames中添加图片后(每次创建一个)并且唤醒其他线程(这里只唤醒一个线程)才能继续执行加载图片。如此,每次创建一个图片就会唤醒一个线程去加载,这个过程其实就是一个典型的生产者-消费者模式。下面通过NSCondition实现这个流程的控制:
KCMainViewController.h
<span style="color: green;">// // KCMainViewController.h // MultiThread // // Created by Kenshin Cui on 14-3-22. // Copyright (c) 2014年 Kenshin Cui. All rights reserved. // </span><span style="color: blue;">#import </span><span style="color: rgb(163, 21, 21);"><UIKit/UIKit.h> </span><span style="color: black;">@</span><span style="color: blue;">interface </span><span style="color: black;">KCMainViewController : UIViewController </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 图片资源存储容器 @</span><span style="color: blue;">property </span><span style="color: black;">(atomic,strong) NSMutableArray *imageNames; </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 当前加载的图片索引(图片链接地址连续) @</span><span style="color: blue;">property </span><span style="color: black;">(atomic,assign) </span><span style="color: blue;">int </span><span style="color: black;">currentIndex; @end</span>
KCMainViewController.m
<span style="color: green;">// // 线程控制 // MultiThread // // Created by Kenshin Cui on 14-3-22. // Copyright (c) 2014年 Kenshin Cui. All rights reserved. // </span><span style="color: blue;">#import </span><span style="color: rgb(163, 21, 21);">"KCMainViewController.h" </span><span style="color: blue;">#import </span><span style="color: rgb(163, 21, 21);">"KCImageData.h" </span><span style="color: blue;">#define </span><span style="color: black;">ROW_COUNT 5 </span><span style="color: blue;">#define </span><span style="color: black;">COLUMN_COUNT 3 </span><span style="color: blue;">#define </span><span style="color: black;">ROW_HEIGHT 100 </span><span style="color: blue;">#define </span><span style="color: black;">ROW_WIDTH ROW_HEIGHT </span><span style="color: blue;">#define </span><span style="color: black;">CELL_SPACING 10 </span><span style="color: blue;">#define </span><span style="color: black;">IMAGE_COUNT 9 @</span><span style="color: blue;">interface </span><span style="color: black;">KCMainViewController (){ NSMutableArray *_imageViews; NSCondition *_condition; } @end @implementation KCMainViewController </span><span style="color: blue;">#pragma </span><span style="color: black;">mark - 事件 - (</span><span style="color: blue;">void</span><span style="color: black;">)viewDidLoad { [super viewDidLoad]; [self layoutUI]; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark - 内部私有方法 </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 界面布局 -(</span><span style="color: blue;">void</span><span style="color: black;">)layoutUI{ </span><span style="color: green;">//创建多个图片控件用于显示图片 </span><span style="color: black;">_imageViews=[NSMutableArray </span><span style="color: blue;">array</span><span style="color: black;">]; </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">r=0; r<ROW_COUNT; r++) { </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">c=0; c<COLUMN_COUNT; c++) { UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(c*ROW_WIDTH+(c*CELL_SPACING), r*ROW_HEIGHT+(r*CELL_SPACING ), ROW_WIDTH, ROW_HEIGHT)]; imageView.contentMode=UIViewContentModeScaleAspectFit; [self.view addSubview:imageView]; [_imageViews addObject:imageView]; } } UIButton *btnLoad=[UIButton buttonWithType:UIButtonTypeRoundedRect]; btnLoad.frame=CGRectMake(50, 500, 100, 25); [btnLoad setTitle:@</span><span style="color: rgb(163, 21, 21);">"加载图片" </span><span style="color: black;">forState:UIControlStateNormal]; [btnLoad addTarget:self action:@selector(loadImageWithMultiThread) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btnLoad]; UIButton *btnCreate=[UIButton buttonWithType:UIButtonTypeRoundedRect]; btnCreate.frame=CGRectMake(160, 500, 100, 25); [btnCreate setTitle:@</span><span style="color: rgb(163, 21, 21);">"创建图片" </span><span style="color: black;">forState:UIControlStateNormal]; [btnCreate addTarget:self action:@selector(createImageWithMultiThread) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:btnCreate]; </span><span style="color: green;">//创建图片链接 </span><span style="color: black;">_imageNames=[NSMutableArray </span><span style="color: blue;">array</span><span style="color: black;">]; </span><span style="color: green;">//初始化锁对象 </span><span style="color: black;">_condition=[[NSCondition alloc]init]; _currentIndex=0; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 创建图片 -(</span><span style="color: blue;">void</span><span style="color: black;">)createImageName{ [_condition lock]; </span><span style="color: green;">//如果当前已经有图片了则不再创建,线程处于等待状态 </span><span style="color: blue;">if </span><span style="color: black;">(_imageNames.count>0) { NSLog(@</span><span style="color: rgb(163, 21, 21);">"createImageName wait, current:%i"</span><span style="color: black;">,_currentIndex); [_condition wait]; }</span><span style="color: blue;">else</span><span style="color: black;">{ NSLog(@</span><span style="color: rgb(163, 21, 21);">"createImageName work, current:%i"</span><span style="color: black;">,_currentIndex); </span><span style="color: green;">//生产者,每次生产1张图片 </span><span style="color: black;">[_imageNames addObject:[NSString stringWithFormat:@</span><span style="color: rgb(163, 21, 21);">"http://images.cnblogs.com/cnblogs_com/kenshincui/613474/o_%i.jpg"</span><span style="color: black;">,_currentIndex++]]; </span><span style="color: green;">//创建完图片则发出信号唤醒其他等待线程 </span><span style="color: black;">[_condition signal]; } [_condition unlock]; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 加载图片并将图片显示到界面 -(</span><span style="color: blue;">void</span><span style="color: black;">)loadAnUpdateImageWithIndex:(</span><span style="color: blue;">int </span><span style="color: black;">)index{ </span><span style="color: green;">//请求数据 </span><span style="color: black;">NSData *data= [self requestData:index]; </span><span style="color: green;">//更新UI界面,此处调用了GCD主线程队列的方法 </span><span style="color: black;">dispatch_queue_t mainQueue= dispatch_get_main_queue(); dispatch_sync(mainQueue, ^{ UIImage *image=[UIImage imageWithData:data]; UIImageView *imageView= _imageViews[index]; imageView.image=image; }); } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 请求图片数据 -(NSData *)requestData:(</span><span style="color: blue;">int </span><span style="color: black;">)index{ NSData *data; NSString *name; name=[_imageNames lastObject]; [_imageNames removeObject:name]; </span><span style="color: blue;">if</span><span style="color: black;">(name){ NSURL *url=[NSURL URLWithString:name]; data=[NSData dataWithContentsOfURL:url]; } </span><span style="color: blue;">return </span><span style="color: black;">data; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 加载图片 -(</span><span style="color: blue;">void</span><span style="color: black;">)loadImage:(NSNumber *)index{ </span><span style="color: blue;">int </span><span style="color: black;">i=(</span><span style="color: blue;">int</span><span style="color: black;">)[index integerValue]; </span><span style="color: green;">//加锁 </span><span style="color: black;">[_condition lock]; </span><span style="color: green;">//如果当前有图片资源则加载,否则等待 </span><span style="color: blue;">if </span><span style="color: black;">(_imageNames.count>0) { NSLog(@</span><span style="color: rgb(163, 21, 21);">"loadImage work,index is %i"</span><span style="color: black;">,i); [self loadAnUpdateImageWithIndex:i]; [_condition broadcast]; }</span><span style="color: blue;">else</span><span style="color: black;">{ NSLog(@</span><span style="color: rgb(163, 21, 21);">"loadImage wait,index is %i"</span><span style="color: black;">,i); NSLog(@</span><span style="color: rgb(163, 21, 21);">"%@"</span><span style="color: black;">,[NSThread currentThread]); </span><span style="color: green;">//线程等待 </span><span style="color: black;">[_condition wait]; NSLog(@</span><span style="color: rgb(163, 21, 21);">"loadImage resore,index is %i"</span><span style="color: black;">,i); </span><span style="color: green;">//一旦创建完图片立即加载 </span><span style="color: black;">[self loadAnUpdateImageWithIndex:i]; } </span><span style="color: green;">//解锁 </span><span style="color: black;">[_condition unlock]; } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark - UI调用方法 </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 异步创建一张图片链接 -(</span><span style="color: blue;">void</span><span style="color: black;">)createImageWithMultiThread{ dispatch_queue_t globalQueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); </span><span style="color: green;">//创建图片链接 </span><span style="color: black;">dispatch_async(globalQueue, ^{ [self createImageName]; }); } </span><span style="color: blue;">#pragma </span><span style="color: black;">mark 多线程下载图片 -(</span><span style="color: blue;">void</span><span style="color: black;">)loadImageWithMultiThread{ </span><span style="color: blue;">int </span><span style="color: black;">count=ROW_COUNT*COLUMN_COUNT; dispatch_queue_t globalQueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); </span><span style="color: blue;">for </span><span style="color: black;">(</span><span style="color: blue;">int </span><span style="color: black;">i=0; i<count; ++i) { </span><span style="color: green;">//加载图片 </span><span style="color: black;">dispatch_async(globalQueue, ^{ [self loadImage:[NSNumber numberWithInt:i]]; }); } } @end</span>
运行效果:
在上面的代码中loadImage:方法是消费者,当在界面中点击“加载图片”后就创建了15个消费者线程。在这个过程中每个线程进入图片加载方法之后都会先加锁,加锁之后其他进程是无法进入“加锁代码”的。但是第一个线程进入“加锁代码”后去加载图片却发现当前并没有任何图片,因此它只能等待。一旦调用了NSCondition的wait方法后其他线程就可以继续进入“加锁代码”(注意,这一点和前面说的NSLock、@synchronized等是不同的,使用NSLock、@synchronized等进行加锁后无论什么情况下,只要没有解锁其他线程就无法进入“加锁代码”),同时第一个线程处于等待队列中(此时并未解锁)。第二个线程进来之后同第一线程一样,发现没有图片就进入等待状态,然后第三个线程进入。。。如此反复,直到第十五个线程也处于等待。此时点击“创建图片”后会执行createImageName方法,这是一个生产者,它会创建一个图片链接放到imageNames中,然后通过调用NSCondition的signal方法就会在条件等待队列中选择一个线程(该线程会任意选取,假设为线程A)开启,那么此时这个线程就会继续执行。在上面代码中,wati方法之后会继续执行图片加载方法,那么此时线程A启动之后继续执行图片加载方法,当然此时可以成功加载图片。加载完图片之后线程A就会释放锁,整个线程任务完成。此时再次点击”创建图片“按钮重复前面的步骤加载其他图片。
为了说明上面的过程,这里以一个流程图的进行说明,流程图蓝色部分代表15个加载图片的线程,绿色部分表示创建图片资源线程。
在iOS开发中,除了同步锁有时候还会用到一些其他锁类型,在此简单介绍一下:
NSRecursiveLock :递归锁,有时候“加锁代码”中存在递归调用,递归开始前加锁,递归调用开始后会重复执行此方法以至于反复执行加锁代码最终造成死锁,这个时候可以使用递归锁来解决。使用递归锁可以在一个线程中反复获取锁而不造成死锁,这个过程中会记录获取锁和释放锁的次数,只有最后两者平衡锁才被最终释放。
NSDistributedLock:分布锁,它本身是一个互斥锁,基于文件方式实现锁机制,可以跨进程访问。
pthread_mutex_t:同步锁,基于C语言的同步锁机制,使用方法与其他同步锁机制类似。
提示:在开发过程中除非必须用锁,否则应该尽可能不使用锁,因为多线程开发本身就是为了提高程序执行顺序,而同步锁本身就只能一个进程执行,这样不免降低执行效率。
1>无论使用哪种方法进行多线程开发,每个线程启动后并不一定立即执行相应的操作,具体什么时候由系统调度(CPU空闲时就会执行)。
2>更新UI应该在主线程(UI线程)中进行,并且推荐使用同步调用,常用的方法如下:
3>NSThread适合轻量级多线程开发,控制线程顺序比较难,同时线程总数无法控制(每次创建并不能重用之前的线程,只能创建一个新的线程)。
4>对于简单的多线程开发建议使用NSObject的扩展方法完成,而不必使用NSThread。
5>可以使用NSThread的currentThread方法取得当前线程,使用 sleepForTimeInterval:方法让当前线程休眠。
6>NSOperation进行多线程开发可以控制线程总数及线程依赖关系。
7>创建一个NSOperation不应该直接调用start方法(如果直接start则会在主线程中调用)而是应该放到NSOperationQueue中启动。
8>相比NSInvocationOperation推荐使用NSBlockOperation,代码简单,同时由于闭包性使它没有传参问题。
9>NSOperation是对GCD面向对象的ObjC封装,但是相比GCD基于C语言开发,效率却更高,建议如果任务之间有依赖关系或者想要监听任务完成状态的情况下优先选择NSOperation否则使用GCD。
10>在GCD中串行队列中的任务被安排到一个单一线程执行(不是主线程),可以方便地控制执行顺序;并发队列在多个线程中执行(前提是使用异步方法),顺序控制相对复杂,但是更高效。
11>在GDC中一个操作是多线程执行还是单线程执行取决于当前队列类型和执行方法,只有队列类型为并行队列并且使用异步方法执行时才能在多个线程中执行(如果是并行队列使用同步方法调用则会在主线程中执行)。
12>相比使用NSLock,@synchronized更加简单,推荐使用后者。