串行队列
异步派发
不会造成线程阻塞,但是会依次执行派发任务
dispatch_queue_t serialQqueue = dispatch_queue_create("serialQqueue", DISPATCH_QUEUE_SERIAL);
// 异步派发
dispatch_async(serialQqueue, ^{
NSLog(@"---1");
sleep(2);
NSLog(@"1");
});
NSLog(@"-----");
// 异步派发
dispatch_async(serialQqueue, ^{
NSLog(@"---2");
sleep(1);
NSLog(@"2");
});
NSLog(@"end");
image.png
同步派发
依次执行派发任务,会阻塞线程
dispatch_queue_t serialQqueue = dispatch_queue_create("serialQqueue", DISPATCH_QUEUE_SERIAL);
// 同步派发
dispatch_sync(serialQqueue, ^{
NSLog(@"---1");
sleep(2);
NSLog(@"1");
});
NSLog(@"-----");
// 同步派发
dispatch_sync(serialQqueue, ^{
NSLog(@"---2");
sleep(1);
NSLog(@"2");
});
NSLog(@"end");
image.png
先异步派发再同步派发
异步派发时不会造成线程阻塞,同步派发是线程会阻塞,但依次执行派发任务
dispatch_queue_t serialQqueue = dispatch_queue_create("serialQqueue", DISPATCH_QUEUE_SERIAL);
// 异步派发
dispatch_async(serialQqueue, ^{
NSLog(@"---1");
sleep(2);
NSLog(@"1");
});
NSLog(@"-----");
// 同步派发
dispatch_sync(serialQqueue, ^{
NSLog(@"---2");
sleep(1);
NSLog(@"2");
});
NSLog(@"end");
image.png
先同步派发再异步派发
同步派发时线程会阻塞,当执行完派发任务后继续往下执行,异步派发时不会造成线程阻塞
dispatch_queue_t serialQqueue = dispatch_queue_create("serialQqueue", DISPATCH_QUEUE_SERIAL);
// 同步派发
dispatch_sync(serialQqueue, ^{
NSLog(@"---1");
sleep(2);
NSLog(@"1");
});
NSLog(@"-----");
// 异步派发
dispatch_async(serialQqueue, ^{
NSLog(@"---2");
sleep(1);
NSLog(@"2");
});
NSLog(@"end");
image.png
并行队列
异步派发
一起执行,不会造成线程阻塞
dispatch_queue_t concurrencyQueue = dispatch_queue_create("concurrencyQueue", DISPATCH_QUEUE_CONCURRENT);
// 异步派发
dispatch_async(concurrencyQueue, ^{
NSLog(@"---1");
sleep(2);
NSLog(@"1");
});
NSLog(@"-----");
// 异步派发
dispatch_async(concurrencyQueue, ^{
NSLog(@"---2");
sleep(1);
NSLog(@"2");
});
NSLog(@"end");
image.png
同步派发
依次执行,会造成线程阻塞,等同于串行队列同步派发
dispatch_queue_t concurrencyQueue = dispatch_queue_create("concurrencyQueue", DISPATCH_QUEUE_CONCURRENT);
// 同步派发
dispatch_sync(concurrencyQueue, ^{
NSLog(@"---1");
sleep(2);
NSLog(@"1");
});
NSLog(@"-----");
// 同步派发
dispatch_sync(concurrencyQueue, ^{
NSLog(@"---2");
sleep(1);
NSLog(@"2");
});
NSLog(@"end");
image.png
先异步派发再同步派发
异步派发时线程不阻塞,派发的任务单独执行,不受线程阻塞影响,同步派发时线程阻塞
dispatch_queue_t concurrencyQueue = dispatch_queue_create("concurrencyQueue", DISPATCH_QUEUE_CONCURRENT);
// 异步派发
dispatch_async(concurrencyQueue, ^{
NSLog(@"---1");
sleep(2);
NSLog(@"1");
});
NSLog(@"-----");
// 同步派发
dispatch_sync(concurrencyQueue, ^{
NSLog(@"---2");
sleep(1);
NSLog(@"2");
});
NSLog(@"end");
image.png
先同步派发再异步派发
同步派发时线程阻塞,当派发的任务执行结束后继续往下执行,异步派发时执行派发操作后继续执行,异步派发的内容单独执行
dispatch_queue_t concurrencyQueue = dispatch_queue_create("concurrencyQueue", DISPATCH_QUEUE_CONCURRENT);
// 同步派发
dispatch_sync(concurrencyQueue, ^{
NSLog(@"---1");
sleep(2);
NSLog(@"1");
});
NSLog(@"-----");
// 异步派发
dispatch_async(concurrencyQueue, ^{
NSLog(@"---2");
sleep(1);
NSLog(@"2");
});
NSLog(@"end");
image.png
网友评论