GCD总结1
2020-09-25 本文已影响0人
Jean_Lina
dispatch_sync、dispatch_async用来控制是否开启新的线程。
串行队列、并发队列决定任务的执行方式。
dispatch_sync:立马在当前线程同步执行任务。
#pragma mark interview1 相互等待,产生死锁1
- (void)question6 {
dispatch_queue_t queue = dispatch_get_main_queue();
NSLog(@"执行任务1");
dispatch_sync(queue, ^{
NSLog(@"主队列执行任务2 -- %@", [NSThread currentThread]);
});
NSLog(@"执行任务3");
}
#pragma mark interview2 相互等待,产生死锁2
- (void)question7 {
NSLog(@"执行任务1");
dispatch_queue_t queue = dispatch_queue_create("SERIALQUEUE", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
NSLog(@"执行任务2 -- %@", [NSThread currentThread]);
dispatch_sync(queue, ^{
NSLog(@"执行任务3");
});
NSLog(@"执行任务4");
});
NSLog(@"执行任务5");
}
(void)question13 {
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
NSLog(@"1");
[self performSelector:@selector(test) withObject:nil];
NSLog(@"3");
});
//打印结果:1 2 3
}
- (void)question14 {
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
NSLog(@"1");
//performSelector withObject afterDelay的本质是:往runloop里面添加NSTimer定时器,子线程默认没有启动runloop。
[self performSelector:@selector(test) withObject:nil afterDelay:.0];
NSLog(@"3");
});
//打印结果:1 3
}
- (void)question15 {
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
NSLog(@"1");
//performSelector withObject afterDelay的本质是:往runloop里面添加NSTimer定时器,子线程默认没有启动runloop。
[self performSelector:@selector(test) withObject:nil afterDelay:.0];
NSLog(@"3");
//启动runloop
[[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
});
//打印结果:1 3 2
}
- (void)question16 {
NSLog(@"1");
//主线程的runloop默认是开启的
[self performSelector:@selector(test) withObject:nil afterDelay:.0];
NSLog(@"3");
//打印结果:1 3 2
}
- (void)test {
NSLog(@"2");
}
- (void)question17 {
NSThread *thread = [[NSThread alloc] initWithBlock:^{
NSLog(@"1");
//为子线程添加一个runloop,不让线程销毁
[[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}];
[thread start];
[self performSelector:@selector(test) onThread:thread withObject:nil waitUntilDone:YES];
//打印结果:1 2
}
- (void)question18 {
NSThread *thread = [[NSThread alloc] initWithBlock:^{
NSLog(@"1");
}];
[thread start];
[self performSelector:@selector(test) onThread:thread withObject:nil waitUntilDone:YES];
//打印结果:1,程序崩溃
}
GCD-1.png
GCD-2.png
产生死锁原因:
使用sync函数往当前串行队列里面添加任务,会卡住当前串行队列(产生死锁)。