iOS多线程
在iOS中每个进程启动后都会建立一个主线程(UI线程),这个线程是其他线程的父线程。由于在iOS中除了主线程,其他子线程是独立于Cocoa Touch的,所以只有主线程可以更新UI界面(新版iOS中,使用其他线程更新UI可能也能成功,但是不推荐)。iOS中多线程使用并不复杂,关键是如何控制好各个线程的执行顺序、处理好资源竞争问题。常用的多线程开发有三种方式:
1.NSThread
2.NSOperation
3.GCD
三种方式是随着iOS的发展逐渐引入的,所以相比而言后者比前者更加简单易用,并且GCD也是目前苹果官方比较推荐的方式(它充分利用了多核处理器的运算性能).但是今天我们一起来学习一下NSThread.
NSThread
NSThread是轻量级的多线程开发,使用起来也并不复杂,但是使用NSThread需要自己管理线程生命周期。
1):创建和启动线程
创建NSThread有2种方法.
使用类方法+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument直接将操作添加到线程中并启动
使用对象方法- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(id)argument 创建一个线程对象,然后调用start方法启动线程。
上面2种方式的本质是将target对象的selector方法装换为线程执行体,其中selector方法最多可以接收一个参数,而argument就代表传给selector方法的参数.
下面看一个小例子:
- (void)viewDidLoad {
[super viewDidLoad];
[self testOne];
}
//创建和启动线程
-(void)testOne{
for(int i = 0 ; i < 10 ; i++)
{
NSLog(@"testOne:%@---%d" , [NSThread currentThread], i);
//[NSThread currentThread]返回当前执行的线程对象
// 创建线程对象
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(run) object:nil];
//启动新线程
[thread start];
//[NSThread sleepForTimeInterval:0.001];
// 创建并启动新线程
//[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
}
}
- (void)run
{
for(int i = 0 ; i < 10 ; i++)
{
//设置子线程名字
[[NSThread currentThread] setName:@"run"];
NSLog(@"run:%@----%d" , [NSThread currentThread], i);
}
}
打印输出结果(部分结果):
2016-01-14 14:11:17.868 NSTread[4604:1061376] testOne:<NSThread: 0x7c24bf20>{number = 1, name = main}---0
2016-01-14 14:11:17.869 NSTread[4604:1061376] testOne:<NSThread: 0x7c24bf20>{number = 1, name = main}---1
2016-01-14 14:11:17.869 NSTread[4604:1061376] testOne:<NSThread: 0x7c24bf20>{number = 1, name = main}---2
2016-01-14 14:11:17.869 NSTread[4604:1061485] run:<NSThread: 0x7c15ce80>{number = 2, name = run}----0
2016-01-14 14:11:17.869 NSTread[4604:1061376] testOne:<NSThread: 0x7c24bf20>{number = 1, name = main}---3
2016-01-14 14:11:17.869 NSTread[4604:1061486] run:<NSThread: 0x7c05b9b0>{number = 3, name = run}----0
2016-01-14 14:11:17.869 NSTread[4604:1061376] testOne:<NSThread: 0x7c24bf20>{number = 1, name = main}---4
2016-01-14 14:11:17.869 NSTread[4604:1061376] testOne:<NSThread: 0x7c24bf20>{number = 1, name = main}---5
由上面的结果我们来了解另一个概念:
2:线程的状态
当线程被创建并启动以后,它既不是一启动就进入执行状态,也不是一直处于执行状态.即使线程开始运行以后,它也不可能一直"霸占"着 CPU 独自运行.所以 CPU 需要在多个线程之间切换,于是线程的状态也会在运行和就绪状态 之间进行切换.
当程序创建一个线程之后,该线程就处于新建状态,此时它和其他的 OC 对象一样,仅仅由系统为其分配了内存,并初始化了其成员变量的值.此时的线程对象没有表现出任何的动态特征,程序也不会执行线程的执行体.
当线程对象调用start方法之后,程序处于就绪状态,系统会为其创建方法调用栈和计数器,处于这种状态中的线程并没有开始运行,它只是表示该线程可以运行了,至于该线程何时开始运行,取决于系统的调度.
由上面的例子我们可以看到当调用了start 方法来启动当前线程,当前线程并没有立即执行,而是等到主线程执行到2事,子线程才开始执行.
线程状态分为isExecuting(正在执行)、isFinished(已经完成)、isCancellled(已经取消)三种。其中取消状态程序可以干预设置,只要调用线程的cancel方法即可。但是需要注意在主线程中仅仅能设置线程状态,并不能真正停止当前线程,如果要终止线程必须在线程中调用exist方法,这是一个静态方法,调用该方法可以退出当前线程。
注意:如果程序希望调用子线程的start方法后立即执行,程序可以使用 [NSThread sleepForTimeInterval:0.001];让当前运行的线程(主线程)睡眠1毫秒,1毫秒足够了,因为这1毫秒内 CPU 并不会空闲,它回去执行另一个处于就绪状态的线程,这样就可以让子线程立即获得执行.
3:终止子线程
线程会以以下3种之一结束,结束就处于死亡状态.
1)线程执行体方法执行完成,线程正常结束.
2)线程执行过程中出错.
3)直接调用 NSThread类的exit方法来中止当前正在执行的线程.
注意:当主线程结束时,其他线程不受任何影响,并不会随之结束.一旦子线程启动起来后,它就拥有和主线程相同的地位,它不会搜主线程影响.
4:线程睡眠
前面已经使用过了,如果需要让当前执行的线程暂停一段时间,并进入阻塞状态,则可以通过调用NSThread的两个类方法:
+ (void)sleepUntilDate:(NSDate *)date; 让当前正在执行的线程暂停到 date, 并进入阻塞.
+ (void)sleepForTimeInterval:(NSTimeInterval)ti; 让当前正在执行的线程暂停 ti秒,并进入阻塞状态.
5:线程优先级
每个线程执行时都具有一定的优先级,优先级高的线程获得较多的执行机会,而优先级低的线程获得较少的执行机会,每个子线程默认的优先级是0.5.有相应的方法设置获取优先级:
+ (double)threadPriority; 获取优先级
+ (BOOL)setThreadPriority:(double)p; 设置优先级(参数服务0.0-1.0)
@property double threadPriority;
//改变线程优先级
-(void)testPriority{
NSLog(@"UI线程的优先级为:%g" , [NSThread threadPriority]);
// 创建第一个线程对象
NSThread* thread1 = [[NSThread alloc]
initWithTarget:self selector:@selector(run) object:nil];
// 设置第一个线程对象的名字
thread1.name = @"线程A";
NSLog(@"线程A的优先级为:%g" , thread1.threadPriority);
// 设置使用最低优先级
thread1.threadPriority = 0.0;
// 创建第二个线程对象
NSThread* thread2 = [[NSThread alloc]
initWithTarget:self selector:@selector(run) object:nil];
// 设置第二个线程对象的名字
thread2.name = @"线程B";
NSLog(@"线程B的优先级为:%g" , thread2.threadPriority);
// 设置使用最高优先级
thread2.threadPriority = 1.0;
// 启动2个线程
[thread1 start];
[thread2 start];
}
- (void)run
{
for(int i = 0 ; i < 2 ; i++)
{
//设置子线程名字
NSLog(@"run:%@----%d" , [NSThread currentThread], i);
}
}
打印结果如下:
2016-01-14 14:47:39.099 NSTread[5005:1193424] UI线程的优先级为:0.5
2016-01-14 14:47:39.099 NSTread[5005:1193424] 线程A的优先级为:0.5
2016-01-14 14:47:39.099 NSTread[5005:1193424] 线程B的优先级为:0.5
2016-01-14 14:47:39.100 NSTread[5005:1193543] run:<NSThread: 0x7b994960>{number = 3, name = 线程B}----0
2016-01-14 14:47:39.100 NSTread[5005:1193543] run:<NSThread: 0x7b994960>{number = 3, name = 线程B}----1
2016-01-14 14:47:39.100 NSTread[5005:1193542] run:<NSThread: 0x7a636c80>{number = 2, name = 线程A}----0
2016-01-14 14:47:39.100 NSTread[5005:1193542] run:<NSThread: 0x7a636c80>{number = 2, name = 线程A}----1
实例:远程下载网络图片
在资源下载过程中,由于网络原因有时候很难保证下载时间,如果不使用多线程可能用户完成一个下载操作需要长时间的等待,这个过程中无法进行其他操作。下面演示一个采用多线程下载图片的过程,在这个示例中点击按钮会启动一个线程去下载图片,下载完成后使用UIImageView将图片显示到界面中。可以看到用户点击完下载按钮后,不管图片是否下载完成都可以继续操作界面,不会造成阻塞。
#import "ViewController.h"
@interface ViewController (){
UIImageView *_imageView;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self createUI];
}
/**
* 界面布局
*/
-(void)createUI{
_imageView=[[UIImageView alloc]initWithFrame:CGRectMake(60, 80, 200, 300)];
_imageView.contentMode=UIViewContentModeScaleAspectFit;
_imageView.backgroundColor=[UIColor grayColor];
[self.view addSubview:_imageView];
UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
button.frame=CGRectMake(100, 400,100, 40);
[button setTitle:@"下载图片" forState:UIControlStateNormal];
[button setBackgroundColor:[UIColor redColor]];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[button addTarget:self action:@selector(loadImageWithMultiThread) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
/**
* 多线程下载图片
*/
-(void)loadImageWithMultiThread{
//方法1:使用对象方法
//创建一个线程,第一个参数是请求的操作,第二个参数是线程方法执行参数
//NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector(loadImage) object:nil];
//启动一个线程,注意启动一个线程并非就一定立即执行,而是处于就绪状态,当系统调度时才真正执行
//[thread start];
//方法2:使用类方法
[NSThread detachNewThreadSelector:@selector(loadImage) toTarget:self withObject:nil];
}
/**
* 加载图片
*/
-(void)loadImage{
//请求数据
NSURL *url=[NSURL URLWithString:@"http://image48.360doc.com/DownloadImg/2011/12/1409/20015563_1.jpg"];
NSData *data=[NSData dataWithContentsOfURL:url];
/*
将数据显示到UI控件,注意只能在主线程中更新UI,
另外performSelectorOnMainThread方法是NSObject的分类方法,每个NSObject对象都有此方法,
所以它调用的selector方法是当前调用控件的方法,例如使用UIImageView调用的时候selector就是UIImageView的方法
Object:代表调用方法的参数,不过只能传递一个参数(多个参数轻定义成对象类型)
waitUntilDone:是否线程任务完成执行
*/
[self performSelectorOnMainThread:@selector(updateImage:) withObject:data waitUntilDone:YES];
}
//将图片显示到界面
-(void)updateImage:(NSData *)imageData{
UIImage *image=[UIImage imageWithData:imageData];
_imageView.image=image;
}
界面效果如下:(图一未下载图片,图二下载图片成功)
程序比较简单,但是需要注意执行步骤:当点击了“加载图片”按钮后启动一个新的线程,这个过程中UI线程是不会阻塞的,用户可以进行其他操作,大约几秒之后图片下载完成,此时调用UI线程将图片显示到界面中(这个过程瞬间完成)。另外前面也提到过,更新UI的时候使用UI线程,这里调用了NSObject的分类扩展方法,调用UI线程完成更新.
多个线程并发
上面这个演示并没有演示多个子线程操作之间的关系,现在不妨在界面中多加载几张图片,每个图片都来自远程请求。
#import <Foundation/Foundation.h>
@interface SHImageData : NSObject
//索引
@property (nonatomic,assign) NSInteger index;
//图片数据
@property (nonatomic,strong) NSData *data;
@end
#import "SHImageData.h"
@implementation SHImageData
@end
#import "MainViewController.h"
#import "SHImageData.h"
#define IMAGE_SPACE 8
#define IMAGE_WIDTH 150
#define IMAGE_HEIGHT 80
@interface MainViewController (){
NSMutableArray *_imageViewArray;
}
@end
@implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self layoutUI];
}
#pragma mark 界面布局
-(void)layoutUI{
//创建多个图片控件用于显示图片
_imageViewArray=[NSMutableArray array];
for (int i=0; i<2; i++) {
for (int j=0; j<2; j++) {
UIImageView *imageView=[[UIImageView alloc]initWithFrame:
CGRectMake(IMAGE_SPACE+j*(IMAGE_SPACE+IMAGE_WIDTH),64+IMAGE_SPACE+i*(IMAGE_SPACE+IMAGE_HEIGHT) , IMAGE_WIDTH, IMAGE_HEIGHT)];
imageView.contentMode=UIViewContentModeScaleAspectFit;
[self.view addSubview:imageView];
[_imageViewArray addObject:imageView];
}
}
UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
button.frame=CGRectMake(100, 260,100, 40);
[button setTitle:@"下载图片" forState:UIControlStateNormal];
[button setBackgroundColor:[UIColor redColor]];
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[button addTarget:self action:@selector(loadImageWithMultiThread)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
//多线程下载图片
-(void)loadImageWithMultiThread{
//创建多个线程用于填充图片
for (int i=0; i<4; i++) {
//[NSThread detachNewThreadSelector:@selector(loadImage:) toTarget:self withObject:[NSNumber numberWithInt:i]];
NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector(loadImage:) object:[NSNumber numberWithInt:i]];
thread.name=[NSString stringWithFormat:@"myThread%i",i];//设置线程名称
[thread start];
}
}
//将图片显示到界面
-(void)updateImage:(SHImageData *)imageData{
UIImage *image=[UIImage imageWithData:imageData.data];
UIImageView *imageView= _imageViewArray[imageData.index];
imageView.image=image;
}
//加载图片
-(void)loadImage:(NSNumber *)index{
//NSLog(@"%i",i);
//currentThread方法可以取得当前操作线程
NSLog(@"current thread:%@",[NSThread currentThread]);
NSInteger i=[index integerValue];
NSURL *url=[NSURL URLWithString:@"http://g.hiphotos.baidu.com/zhidao/pic/item/37d3d539b6003af33c9aba42362ac65c1038b6eb.jpg"];
NSData *data=[NSData dataWithContentsOfURL:url];
if (data) {
SHImageData *imageData=[[SHImageData alloc]init];
imageData.index=i;
imageData.data=data;
[self performSelectorOnMainThread:@selector(updateImage:) withObject:imageData waitUntilDone:YES];
}
}
效果如下:
通过NSThread的currentThread可以取得当前操作的线程,其中会记录线程名称name和编号number,需要注意主线程编号永远为1。多个线程虽然按顺序启动,但是实际执行未必按照顺序加载照片(loadImage:方法未必依次创建,可以通过在loadImage:中打印索引查看),因为线程启动后仅仅处于就绪状态,实际是否执行要由CPU根据当前状态调度。
从上面的运行效果大家不难发现,图片并未按顺序加载,原因有两个:第一,每个线程的实际执行顺序并不一定按顺序执行(虽然是按顺序启动);
第二,每个线程执行时实际网络状况很可能不一致。当然网络问题无法改变,只能尽可能让网速更快,但是可以改变线程的优先级,优先执行某个线程。线程优先级范围为0~1,值越大优先级越高,每个线程的优先级默认为0.5。
扩展--NSObject分类扩展方法
为了简化多线程开发过程,苹果官方对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:在主线程上执行一个方法(前面已经使用过)。