iOS GCD初识.md
2020-07-22 本文已影响0人
儒徒
串行队列
- 串行队列:操作是按顺序执行的,并且都在同一个线程上输出
- 一个串行队列对应只有一个线程,因此同时只能执行一个操作,先追加的操作先执行。执行很多操作的时候就好像人们排队买东西一样,先来后到。
同步执行
dispatch_queue_t queue = dispatch_queue_create("com.kenan.comQueue", DISPATCH_QUEUE_SERIAL);
//dispatch_sync::执行方式-同步步,会阻塞运行
dispatch_sync(queue, ^{
NSLog(@"1%@",[NSThread currentThread]);
});
NSLog(@"2%@",[NSThread currentThread]);
dispatch_sync(queue, ^{
NSLog(@"3%@",[NSThread currentThread]);
});
NSLog(@"4%@",[NSThread currentThread]);
dispatch_sync(queue, ^{
NSLog(@"5%@",[NSThread currentThread]);
});
NSLog(@"6%@",[NSThread currentThread]);
串行-同步Snip20200715_50.png
异步执行
dispatch_queue_t queue = dispatch_queue_create("com.kenan.comQueue", DISPATCH_QUEUE_SERIAL);
//dispatch_async:执行方式-异步,不会阻塞运行
dispatch_async(queue, ^{
NSLog(@"1%@",[NSThread currentThread]);
});
NSLog(@"2%@",[NSThread currentThread]);
dispatch_async(queue, ^{
NSLog(@"3%@",[NSThread currentThread]);
});
NSLog(@"4%@",[NSThread currentThread]);
dispatch_async(queue, ^{
NSLog(@"5%@",[NSThread currentThread]);
});
NSLog(@"6%@",[NSThread currentThread]);
串行-异步Snip20200715_51.png
并发队列
同步执行
dispatch_queue_t conccurentQueue = dispatch_queue_create("com.kenan.comQueue", DISPATCH_QUEUE_CONCURRENT);
//dispatch_sync::执行方式-同步步,会阻塞运行。不会开辟线程。
dispatch_sync(conccurentQueue, ^{
NSLog(@"1%@",[NSThread currentThread]);
});
NSLog(@"2%@",[NSThread currentThread]);
dispatch_sync(conccurentQueue, ^{
NSLog(@"3%@",[NSThread currentThread]);
});
NSLog(@"4%@",[NSThread currentThread]);
dispatch_sync(conccurentQueue, ^{
NSLog(@"5%@",[NSThread currentThread]);
});
NSLog(@"6%@",[NSThread currentThread]);
并发同步Snip20200715_52.png
异步执行
dispatch_queue_t conccurentQueue = dispatch_queue_create("com.kenan.comQueue", DISPATCH_QUEUE_CONCURRENT);
//dispatch_async:执行方式-异步,不会阻塞运行。会开辟线程,线程数量取决于GCD
dispatch_async(conccurentQueue, ^{
NSLog(@"1%@",[NSThread currentThread]);
});
NSLog(@"2%@",[NSThread currentThread]);
dispatch_async(conccurentQueue, ^{
NSLog(@"3%@",[NSThread currentThread]);
});
NSLog(@"4%@",[NSThread currentThread]);
dispatch_async(conccurentQueue, ^{
NSLog(@"5%@",[NSThread currentThread]);
});
NSLog(@"6%@",[NSThread currentThread]);
并行-异步Snip20200715_53.png