1.异步+并发
dispatch_queue_t queue = dispatch_queue_create("com.demo.conQueue", DISPATCH_QUEUE_CONCURRENT);
NSLog(@"1");
dispatch_async(queue, ^{
// 还是会按顺序执行
NSLog(@"%@ 2-1",[NSThread currentThread]);
NSLog(@"%@ 2-2",[NSThread currentThread]);
NSLog(@"%@ 2-3",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"%@ 3",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"%@ 4",[NSThread currentThread]);
});
NSLog(@"5");
// 结果
/*
1
5
<NSThread: 0x60000174dfc0>{number = 3, name = (null)} 2-1
<NSThread: 0x600001704540>{number = 6, name = (null)} 3
<NSThread: 0x600001758f40>{number = 7, name = (null)} 4
<NSThread: 0x60000174dfc0>{number = 3, name = (null)} 2-2
<NSThread: 0x60000174dfc0>{number = 3, name = (null)} 2-3
*/
2.同步/异步 + 串行队列
dispatch_queue_t queue = dispatch_queue_create("com.demo.serialQueue", DISPATCH_QUEUE_SERIAL);
NSLog(@"1");
// 异步+串行 --> 能够开辟一条新线程
dispatch_async(queue, ^{
NSLog(@"%@ 2",[NSThread currentThread]);
// 死锁,同步 + 当前队列 --> 死锁
dispatch_sync(queue, ^{
NSLog(@"3");
});
NSLog(@"%@ 4",[NSThread currentThread]);
});
NSLog(@"5");
// 结果
/*
1
5
<NSThread: 0x600001749100>{number = 6, name = (null)} 2
死锁了
*/
网友评论