复习下线程的基础知识, 这里主要是参考文顶顶多线程篇复习写的。
一、简单说明
线程间通信:在1个进程中,线程往往不是孤立存在的,多个线程之间需要经常进行通信
线程间通信的体现
- 1个线程传递数据给另1个线程
- 在1个线程中执行完特定任务后,转到另1个线程继续执行任务
线程间通信常用方法
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thread withObject:(id)arg waitUntilDone:(BOOL)wait;
线程间通信示例 – 图片下载
代码示例
@interface ViewController ()
@property (strong, nonatomic) UIImageView *imageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 20, 300, 300)];
_imageView.backgroundColor = [UIColor redColor];
[self.view addSubview:_imageView];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//在子线程下载
[self performSelectorInBackground:@selector(download) withObject:nil];
}
/**
* 下载图片
*/
- (void)download {
NSLog(@"download---%@", [NSThread currentThread]);
// 1.图片地址,其实是一行
NSString *urlStr = @"https://timgsa.baidu.com/timg?image&quality=80"
@"&size=b9999_10000&sec=1559061649110&di=adfd3a30f3bb4868722529859d14ae9d"
@"&imgtype=0&src=http%3A%2F%2Fpic31.nipic.com%2F20130719%2F9885883_095141604000_2.jpg";
NSURL *url = [NSURL URLWithString:urlStr];
// 2.根据地址下载图片的二进制数据(这句代码最耗时)
NSLog(@"---begin");
NSData *data = [NSData dataWithContentsOfURL:url];
NSLog(@"---end");
// 3.设置图片
UIImage *image = [UIImage imageWithData:data];
// 4.回到主线程,刷新UI界面(为了线程安全)
[self performSelectorOnMainThread:@selector(downloadFinished:) withObject:image waitUntilDone:NO];
// [self performSelector:@selector(downloadFinished:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
// [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES];
NSLog(@"-----done----");
}
- (void)downloadFinished:(UIImage *)image {
self.imageView.image = image;
NSLog(@"downloadFinished---%@", [NSThread currentThread]);
}
@end
网友评论