#import "GCD.h"
@interface GCD ()
@property (strong,nonatomic) UIImageView * backImage;
@end
@implementation GCD
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self gcdDemo3];
self.backImage = [[UIImageView alloc]initWithFrame:self.view.bounds];
[self.view addSubview:self.backImage];
}
//mark- GCD常见代码
/*
同步执行方法
*/
- (void)gcdDemo1{
//创建队列
dispatch_queue_t q = dispatch_get_global_queue(0, 0);
dispatch_queue_t q1 = dispatch_get_global_queue(0, 0);
dispatch_queue_t q2 = dispatch_get_global_queue(0, 0);
//把任务添加到队列
//定义任务
void(^task1)() = ^{
NSLog(@"%@",[NSThread currentThread]);
};
//2.2 添加任务到队列,并且会执行
dispatch_sync(q, task1);
dispatch_sync(q1, ^{
NSLog(@"111");
});
dispatch_sync(q2, ^{
NSLog(@"222");
});
}
/*
异步执行
*/
-(void)gcdDemo2{
//创建队列
dispatch_queue_t q = dispatch_get_global_queue(0, 0);
dispatch_queue_t q1 = dispatch_get_global_queue(0, 0);
dispatch_queue_t q2 = dispatch_get_global_queue(0, 0);
//把任务添加到队列
//定义任务
void(^task1)() = ^{
NSLog(@"%@",[NSThread currentThread]);
};
//2.2 添加任务到队列,并且会执行
dispatch_async(q, task1);
dispatch_async(q1, ^{
NSLog(@"111");
});
dispatch_async(q2, ^{
NSLog(@"222");
});
}
-(void)gcdDemo3{
//指定任务执行方法--异步
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//耗时操作
NSLog(@"%@",[NSThread currentThread]);
NSURL *url = [[NSURL alloc]initWithString:@"http://pic6.huitu.com/res/20130116/84481_20130116142820494200_1.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
// 更新UI 负责在主线程上调度的队列 这个地方用同步和异步都是一样的
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"%@",[NSThread currentThread]);
self.backImage.image = [UIImage imageWithData:data];
});
});
}
@end