标签:
一、创建多线程的五种方式 |
NSThread * thread=[[NSThread alloc] initWithTarget:self selector:@selector(_update) object:nil];
[NSThread detachNewThreadSelector:@selector(_update) toTarget:self withObject:nil];
[self performSelectorInBackground:@selector(_update) withObject:nil];
NSOperationQueue *queue=[[NSOperationQueue alloc] init]; [queue addOperationWithBlock:^{ for(int i=0;i<50;i++){ printf("子线程\n"); } }];
//第一步开启线程池 NSOperationQueue * queue=[[NSOperationQueue alloc] init]; //设置并发数目 [queue setMaxConcurrentOperationCount:2]; //第二部创建多线程添加到线程池 NSInvocationOperation * thread1=[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(_update1) object:nil]; NSInvocationOperation *thread2=[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(_update2) object:nil]; [thread1 setQueuePriority:NSOperationQueuePriorityVeryLow]; [thread2 setQueuePriority:NSOperationQueuePriorityVeryHigh]; [queue addOperation:thread1]; [queue addOperation:thread2];
二、多线程应用实例,加载图片。 |
考虑到如果加载网络图片会延迟,在一个主线程加载会影响控件的渲染,此时可以采取多线程,异步加载完成后刷新UI。
通过为UIImageView 增加类目来实现多线程下载。
主要代码:
#import "UIImageView+thread.h" @implementation UIImageView(load) - (void) setImageWithUrl:(NSString *)url{ [self performSelectorInBackground:@selector(_loadImage:) withObject:url]; } - (void) _loadImage:(NSString *)u{ @autoreleasepool { NSURL *url=[NSURL URLWithString:u]; NSData *data=[NSData dataWithContentsOfURL:url]; UIImage *image=[UIImage imageWithData:data]; [self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO]; } }
标签:
原文地址:http://www.cnblogs.com/shouce/p/5464098.html