自己创建的串行队列会不会开启子线程?”以下是测试代码(在主线程执行的):
dispatch_queue_t concurrentQueue = dispatch_queue_create("concurrent.queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_queue_t serialQueue = dispatch_queue_create("serial.queue", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_async(concurrentQueue, ^{
NSLog(@"异步 并发队列 %@", [NSThread currentThread]);
});
dispatch_async(serialQueue, ^{
NSLog(@"异步 自己创建的串行队列 %@", [NSThread currentThread]);
});
dispatch_async(mainQueue, ^{
NSLog(@"异步 主队列 %@", [NSThread currentThread]);
});
dispatch_sync(concurrentQueue, ^{
NSLog(@"同步 并发队列 %@", [NSThread currentThread]);
});
dispatch_sync(serialQueue, ^{
NSLog(@"同步 自己创建的串行队列 %@", [NSThread currentThread]);
});
// dispatch_sync(mainQueue, ^{
// NSLog(@"同步 主队列 %@", [NSThread currentThread]);
// });
输出结果为:
异步 并发队列 <NSThread: 0x600002c9d700>{number = 3, name = (null)}
异步 自己创建的串行队列 <NSThread: 0x600002cab2c0>{number = 5, name = (null)}
同步 并发队列 <NSThread: 0x600002cc4080>{number = 1, name = main}
同步 自己创建的串行队列 <NSThread: 0x600002cc4080>{number = 1, name = main}
异步 主队列 <NSThread: 0x600002cc4080>{number = 1, name = main}
从结果上看是会创建子线程的,总结一下就是:
并发队列 | 自己创建的串行队列 | 主队列 | |
---|---|---|---|
异步(async) | 子线程 | 子线程 | 主线程 |
同步(sync) | 主线程 | 主线程 | 主线程 |
- 同步:需要等待任务执行完成,所以是直接在当前线程执行。
- 异步:具备开启新线程的能力,不过添加到主队列的任务,都是在主线程执行。
- 使用sync往当前串行队列添加任务,会产生死锁崩溃,可以试一下注释掉的
dispatch_sync(mainQueue,
那段代码。