1.NSThread 每个NSThread对象对应一个线程,真正最原始的线程。
- 优点:NSThread轻量级最低,相对简单。
- 缺点:手动管理所有的线程活动,如生命周期、线程同步、睡眠等。
方法1:使用对象方法
创建一个线程,第一个参数是请求的操作,第二个参数是操作方法的参数
NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector(loadImage) object:nil];
启动一个线程,注意启动一个线程并非就一定立即执行,而是处于就绪状态,当系统调度时才真正执行
[thread start];
方法2:使用类方法
[NSThread detachNewThreadSelector:@selector(loadImage) toTarget:self withObject:nil];
2. NSOperation 自带线程管理的抽象类
- 优点:自带线程周期管理,操作上可更注重自己逻辑。
- 缺点:面向对象的抽象类,只能实现它或者使用它定义好的两个子类:NSInvocationOperation和NSBlockOperation。
创建操作队列
NSOperationQueue *operationQueue=[[NSOperationQueue alloc]init];
operationQueue.maxConcurrentOperationCount=5; 设置最大并发线程数
创建多个线程用于填充图片
方法1:NSBlockOperation
-
创建操作块添加到队列
NSBlockOperation *blockOperation=[NSBlockOperation blockOperationWithBlock:^{ [self loadImage]; }]; [operationQueue addOperation:blockOperation];
-
直接使用操队列添加操作
[operationQueue addOperationWithBlock:^{ [self loadImage]; }];
方法2 : NSInvocationOperation
NSInvocationOperation *invocationOperation=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(loadImage) object:nil];
[operationQueue addOperation:invocationOperation];
-(void)loadImage{
//请求数据
NSData *data= [self requestData];
NSLog(@"%@",[NSThread currentThread]);
//更新UI界面,此处调用了主线程队列的方法(mainQueue是UI主线程)
//利用NSTread
[self performSelectorOnMainThread:@selector(updateImage:) withObject:data waitUntilDone:YES];
//利用NSOperation
// [[NSOperationQueue mainQueue] addOperationWithBlock:^{
// [self updateImage:data];
// }];
}
-(NSData *)requestData{
//对于多线程操作建议把线程操作放到@autoreleasepool中
@autoreleasepool {
NSURL *url=[NSURL URLWithString:@"http://image16.360doc.com/DownloadImg/2010/10/2812/6422708_2.jpg"];
NSData *data=[NSData dataWithContentsOfURL:url];
return data;
}
}
-(void)updateImage:(NSData *)data{
UIImage *image=[UIImage imageWithData:data];
_imageView.image=image;
}