- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//主队列异步
// [self mainQueueAsync];
//主队列同步
// [self mainQueueSync];
//解决死锁
[self demo];
}
//解决死锁
- (void)demo
{
NSLog(@"begin");
//异步
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//主队列 主队列执行任务只有当主线程空闲的时候才能够执行
dispatch_queue_t mainQueue = dispatch_get_main_queue();
//2.任务
dispatch_block_t task1 = ^ {
[NSThread sleepForTimeInterval:1.0];
NSLog(@"task1 %@",[NSThread currentThread]);
};
dispatch_block_t task2 = ^ {
NSLog(@"task2 %@",[NSThread currentThread]);
};
//同步
dispatch_sync(mainQueue, task1);
dispatch_sync(mainQueue, task2);
});
NSLog(@"end");
}
//主队列同步 死锁
- (void)mainQueueSync
{
NSLog(@"begin");
//主队列 主队列执行任务只有当主线程空闲的时候才能够执行
dispatch_queue_t mainQueue = dispatch_get_main_queue();
//2.任务
dispatch_block_t task1 = ^ {
[NSThread sleepForTimeInterval:1.0];
NSLog(@"task1 %@",[NSThread currentThread]);
};
dispatch_block_t task2 = ^ {
NSLog(@"task2 %@",[NSThread currentThread]);
};
//同步
dispatch_sync(mainQueue, task1);
dispatch_sync(mainQueue, task2);
NSLog(@"end");
}
//主队列异步 主队列的任务只在主线程执行 任务是依次执行的
- (void)mainQueueAsync
{
//主队列
dispatch_queue_t mainQueue = dispatch_get_main_queue();
//2.任务
dispatch_block_t task1 = ^ {
[NSThread sleepForTimeInterval:1.0];
NSLog(@"task1 %@",[NSThread currentThread]);
};
dispatch_block_t task2 = ^ {
NSLog(@"task2 %@",[NSThread currentThread]);
};
//异步
dispatch_async(mainQueue, task1);
dispatch_async(mainQueue, task2);
}