iOS 线程 同步、异步 代码记录
同步加并行 :
线程是一块执行,
-(void)concurrentSync {
dispatch_queue_t serialQueue = dispatch_queue_create("com.tian.lawrence",DISPATCH_QUEUE_CONCURRENT);
NSLog(@"1 - %@",[NSThread currentThread]);
dispatch_sync(serialQueue,^{
NSLog(@"2 - %@",[NSThread currentThread]);
});
dispatch_sync(serialQueue,^{
NSLog(@"3 - %@",[NSThread currentThread]);
});
NSLog(@"4 - %@",[NSThread currentThread]);
}
异步加并行:
不会发生阻塞,没有先后顺序
-(void)concurrentAsync {
dispatch_queue_t serialQueue = dispatch_queue_create("com.tian.lawrence",DISPATCH_QUEUE_CONCURRENT);
NSLog(@"1 - %@",[NSThread currentThread]);
dispatch_async(serialQueue,^{
NSLog(@"2 - %@",[NSThread currentThread]);
});
dispatch_async(serialQueue,^{
NSLog(@"3 - %@",[NSThread currentThread]);
});
NSLog(@"4 - %@",[NSThread currentThread]);
}
同步加串行:
线程代码的先后顺序执行,下一个接着执行
-(void)serialSync {
dispatch_queue_t serialQueue = dispatch_queue_create("com.tian.lawrence",DISPATCH_QUEUE_SERIAL);
NSLog(@"1 - %@",[NSThread currentThread]);
dispatch_sync(serialQueue,^{
NSLog(@"2 - %@",[NSThread currentThread]);
});
dispatch_sync(serialQueue,^{
NSLog(@"3 - %@",[NSThread currentThread]);
});
NSLog(@"4 - %@",[NSThread currentThread]);
}
异步加串行:
-(void)serialAsync {
dispatch_queue_t serialQueue = dispatch_queue_create("com.tian.lawrence",DISPATCH_QUEUE_SERIAL);
NSLog(@"1 - %@",[NSThread currentThread]);
dispatch_async(serialQueue,^{
NSLog(@"2 - %@",[NSThread currentThread]);
});
dispatch_async(serialQueue,^{
NSLog(@"3 - %@",[NSThread currentThread]);
});
NSLog(@"4 - %@",[NSThread currentThread]);
}
注意:
在主队列中添加同步任务会产生死锁,进而导致程序崩溃。
如:
-(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view,typically from a nib.
NSLog(@"===========1");
dispatch_sync(dispatch_get_main_queue(),^{
NSLog(@"===========2");
});
NSLog(@"===========3");
}