GCD创建多线程
//串行并行指将耗时操作让多个线程去做
//创建队列,标签是hello,参数填NULL为串行队列
dispatch_queue_t queue = dispatch_queue_create("hello", NULL);
//参数不同是并发队列
dispatch_queue_t queue1 = dispatch_queue_create("hello", DISPATCH_QUEUE_CONCURRENT);
//让当前队列执行任务,决定开不开线程(异步执行不能决定线程数量,要看队列有多少)
//队列同步执行
dispatch_sync(queue, ^{
NSLog(@"%@",[NSThread currentThread]);
});
//队列异步执行(如果执行串行队列只开一个新线程,如果执行并行队列不确定开几个线程)
dispatch_async(queue, ^{
NSLog(@"%@",[NSThread currentThread]);
});
GCD中的主队列
//专门在主队列中调度任务
//获得主队列
dispatch_queue_t queue = dispatch_get_main_queue();
//在主队列不允许开新线程,number = 1,只能在主队列执行
dispatch_async(queue, ^{
//只是把任务放在主线程里面异步执行,但是线程只有一个,会等到主线程不忙的时候再做这个任务
for (int i = 0; i < 5; i++) {
NSLog(@"%@",[NSThread currentThread]);
}
});
GCD中的同步队列(自定义队列)
可以根据GCD队列属性设置执行方式
//创建并发队列
dispatch_queue_t queue = dispatch_queue_create("111", DISPATCH_QUEUE_CONCURRENT);
//将队列同步执行(是通过队列同步实现某种功能)使线程间产生依赖关系
dispatch_sync(queue, ^{
NSLog(@"用户登录");
});
//当登录后让任务异步执行
dispatch_async(queue, ^{
NSLog(@"下载A");
});
dispatch_async(queue, ^{
NSLog(@"下载B");
});
//全局队列和同步队列的区别:
//全局队列没有名称
//全局队列都能拿到这个队列
//在MRC中不需要释放
- (void)globalQueue{
//全局队列不需要创建,只要获取
//1.队列优先级 2.保留参数,现在不用,将来可能用
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
for (int i = 0; i < 5; i++) {
NSLog(@"%@", [NSThread currentThread]);
}
});
}
//线程间通讯
- (void)connection{
dispatch_queue_t queue = dispatch_queue_create("queue", 0);
dispatch_async(queue, ^{
NSLog(@"+++++++%@",[NSThread currentThread]);
NSURL *url = [NSURL URLWithString:@"http://pic13.nipic.com/20110415/1347158_132411659346_2.jpg"];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"-------%@",[NSThread currentThread]);
self.imageView.image = image;
});
});
}
#pragma mark----队列之间的调度(可以跨队列通讯)
- (void)group{
//创建调度组
dispatch_group_t grup = dispatch_group_create();
//创建队列,添加到组
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_group_async(grup, queue, ^{
NSLog(@"下载A%@", [NSThread currentThread]);
});
dispatch_group_async(grup, queue, ^{
NSLog(@"下载B%@", [NSThread currentThread]);
});
//下载完成后获得通知(异步执行,如果更新UI就要获取主队列)
dispatch_group_notify(grup, queue, ^{
NSLog(@"下载完成%@", [NSThread currentThread]);
});
}
#pragma mark----一次性调度(只执行一次)
//无论你触发多少次事件,队列中代码只能执行一次
- (void)once{
static dispatch_once_t once;
dispatch_once(&once, ^{
NSLog(@"只执行一次");
});
NSLog(@"完成");
}