一、串行队列
1、同步运行
dispatch_queue_t queue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL);
dispatch_sync(queue, ^{
NSLog(@"当前线程---%@",[NSThread currentThread]);
});
//结果打印
当前线程---<NSThread: 0x600000441480>{number = 1, name = main}
结论:串行队列-同步运行,不会开启新的线程,线程函数会在创建队列所在的线程中执行(如上,在主线程中创建串行队列,同步线程函数在主线程中执行)
2、异步运行
dispatch_queue_t queue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
NSLog(@"当前线程1---%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"当前线程2---%@",[NSThread currentThread]);
});
//结果打印
当前线程1---<NSThread: 0x600002f3e380>{number = 3, name = (null)}
当前线程2---<NSThread: 0x600002f3e380>{number = 3, name = (null)}
结论:串行队列-异步运行,会开启新的线程,但无论有几个异步函数(dispatch_async),都只开启一个线程
二、并行队列
1、同步运行
dispatch_queue_t queue = dispatch_queue_create("concurrentQueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_sync(queue, ^{
NSLog(@"当前线程---%@",[NSThread currentThread]);
});
//结果打印
当前线程---<NSThread: 0x600000b11480>{number = 1, name = main}
结论:并行队列-同步运行,不会开启新的线程
2、异步运行
dispatch_queue_t queue = dispatch_queue_create("concurrentQueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"当前线程1---%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"当前线程2---%@",[NSThread currentThread]);
});
//结果打印
当前线程1---<NSThread: 0x600001d0c500>{number = 3, name = (null)}
当前线程2---<NSThread: 0x600001df2540>{number = 4, name = (null)}
结论:并行队列-异步执行:会开启新的线程,且有几个异步函数(dispatch_async),就开启几个线程
网友评论