#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.
}
//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
新闻热点
疑难解答