特点
- 专门用来在主线程上调度任务的队列
- 不会开启线程
- 以
先进先出的方式,在主线程空闲时才会调度队列中的任务在主线程执行 - 如果当前主线程正在有任务执行,那么无论主队列中当前被添加了什么任务,都不会被调度
队列获取
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {[self gcdDemo1];[NSThread sleepForTimeInterval:1];NSLog(@"over");}- (void)gcdDemo1 {dispatch_queue_t queue = dispatch_get_main_queue();for (int i = 0; i < 10; ++i) {dispatch_async(queue, ^{NSLog(@"%@ - %d", [NSThread currentThread], i);});NSLog(@"---> %d", i);}NSLog(@"come here");}
在
主线程空闲时才会调度队列中的任务在主线程执行
同步主队列
// MARK: 主队列,同步任务- (void)gcdDemo6 {// 1. 队列dispatch_queue_t q = dispatch_get_main_queue();NSLog(@"!!!");// 2. 同步dispatch_sync(q, ^{NSLog(@"%@", [NSThread currentThread]);});NSLog(@"come here");}
- (void)viewDidLoad {[super viewDidLoad];// 会造成死锁dispatch_sync(dispatch_get_main_queue(), ^{NSLog(@"%@", [NSThread currentThread]);});}
死锁原因:队列引起的循环等待
同步串行
- (void)viewDidLoad {[super viewDidLoad];dispatch_queue_t serialQueue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL);// 不会造成死锁dispatch_sync(serialQueue, ^{NSLog(@"%@", [NSThread currentThread]);});}

注意:使用sync函数往当前串行队列中添加任务,会卡住当前的串行队列(产生死锁)
