串行队列:同一时间队列中只有一个任务在执行,每个任务只有在前一个任务执行完成后才能开始执行。主队列(通过dispatch_get_main_queue()获取,提交至主队列的任务会在主线程中执行) 就是串行队列,也可以使用dispatch_queue_create创建串行队列。
并发队列:这些任务会按照被添加的顺序开始执行。但是任意时刻有多个Block(任务)运行,这个完全是取决于GCD。并发队列可以使用dispatch_queue_create创建,也可以获取进程中的全局队列,全局队列有:高、中(默认)、低三个优先级队列。可以调用dispatch_get_global_queue函数传入相应优先级来访问队列。
同步执行:阻塞当前线程,直到当前block中任务执行完毕才返回。同步并不创建新线程。不能使用sync将任务添加到主队列,这样会造成死锁。
异步执行:不会阻塞当前线程,函数会立即返回, block会在后台异步执行;异步必定会开启新线程。
串行队列+同步执行
dispatch_queue_t serialQueue = dispatch_queue_create("com.lai.www", DISPATCH_QUEUE_SERIAL);
for (int i = 0; i< 1000;i++){
// if (i%2 == 0) {
dispatch_sync(serialQueue, ^{//同步执行
NSLog(@"%@--%d",[NSThread currentThread], i);
});
// }else{
// dispatch_async(serialQueue, ^{//异步执行
// NSLog(@"%@--%d",[NSThread currentThread], i);
// });
// }
}
总结:串行队列+同步执行,任务只会在同一线程执行,并且是当前线程按照顺序执行
串行队列+异步执行
dispatch_queue_t serialQueue = dispatch_queue_create("com.lai.www", DISPATCH_QUEUE_SERIAL);
for (int i = 0; i< 1000;i++){
// if (i%2 == 0) {
// dispatch_sync(serialQueue, ^{//同步执行
// NSLog(@"%@--%d",[NSThread currentThread], i);
// });
// }else{
dispatch_async(serialQueue, ^{//异步执行
NSLog(@"%@--%d",[NSThread currentThread], i);
});
// }
}
总结:串行队列+异步执行,任务不会再当前线程执行,会新开辟一条线程,在使队列中的任务按照顺序在新开辟的线程中执行.
串行队列+(同步执行+异步执行)
dispatch_queue_t serialQueue = dispatch_queue_create("com.lai.www", DISPATCH_QUEUE_SERIAL);
for (int i = 0; i< 1000;i++){
if (i%2 == 0) {
dispatch_sync(serialQueue, ^{//同步执行
NSLog(@"%@--%d",[NSThread currentThread], i);
});
}else{
dispatch_async(serialQueue, ^{//异步执行
NSLog(@"%@--%d",[NSThread currentThread], i);
});
}
}
总结:串行队列+(同步执行+异步执行),其中同步执行的任务会在当前线程执行,异步执行的任务会开辟新的线程执行,然而因为多次在当前线程和开辟的新的线程中切换,所以新开辟的线程可能不一定都是一条.
并发队列+同步执行
dispatch_queue_t serialQueue = dispatch_queue_create("com.lai.www", DISPATCH_QUEUE_CONCURRENT);
for (int i = 0; i< 1000;i++){
// if (i%2 == 0) {
dispatch_sync(serialQueue, ^{//同步执行
NSLog(@"%@--%d",[NSThread currentThread], i);
});
// }else{
// dispatch_async(serialQueue, ^{//异步执行
// NSLog(@"%@--%d",[NSThread currentThread], i);
// });
// }
}
总结:并发队列+同步执行,队列中的任务会在新的线程中按照顺序执行.
并发队列+异步执行
dispatch_queue_t serialQueue = dispatch_queue_create("com.lai.www", DISPATCH_QUEUE_CONCURRENT);
for (int i = 0; i< 1000;i++){
// if (i%2 == 0) {
// dispatch_sync(serialQueue, ^{//同步执行
// NSLog(@"%@--%d",[NSThread currentThread], i);
// });
// }else{
dispatch_async(serialQueue, ^{//异步执行
NSLog(@"%@--%d",[NSThread currentThread], i);
});
// }
}
总结:并发队列+异步执行,队列中的任务会随机开辟多个新的线程执行任务,并且是无序.
并发队列+(同步执行+异步执行)
dispatch_queue_t serialQueue = dispatch_queue_create("com.lai.www", DISPATCH_QUEUE_CONCURRENT);
for (int i = 0; i< 1000;i++){
if (i%2 == 0) {
dispatch_sync(serialQueue, ^{//同步执行
NSLog(@"%@--%d",[NSThread currentThread], i);
});
}else{
dispatch_async(serialQueue, ^{//异步执行
NSLog(@"%@--%d",[NSThread currentThread], i);
});
}
}
总结:并发队列+(同步执行+异步执行),队列中同步执行的任务按顺序在当前线程中执行,队列中异步执行的任务随机开辟新线程无序执行