iOS的多线程问题三丶GCD总结
总的来说GCD总共有以下四种手动模式和两个官方模式
1.并行队列同步任务(不开线程)
2.并行队列异步任务(开线程)
3.串行队列同步任务(不开线程)
4.串行队列异步任务(不开线程)
a.全局队列同步任务(不开线程)
b.全局队列异步任务(开线程)
*注:实际开发中常用的只有两种(全局队列异步任务和串行队列异步任务、其他的几乎无意义)
1.并行队列同步任务(不开线程)
- (void)conCurrentQueueSync {
// 并行队列 DISPATCH_QUEUE_CONCURRENT
// 空 DISPATCH_QUEUE_SERIAL 并行队列开了十个同步任务(一个线程)
dispatch_queue_t queue = dispatch_queue_create("conCurrent",DISPATCH_QUEUE_CONCURRENT);
for (int i = 0; i< 10; i++) {
dispatch_sync(queue, ^{
NSLog(@"testConcurrent %d %@",i,[NSThread currentThread]);
});
} }
2.同步队列异步任务(开线程)
- (void)conCurrentQueueASync {
// 并行队列 DISPATCH_QUEUE_CONCURRENT
// DISPATCH_QUEUE_SERIAL 同步队列开了十个异步任务(十个线程)
dispatch_queue_t queue = dispatch_queue_create("conCurrent",DISPATCH_QUEUE_CONCURRENT);
for (int i = 0; i< 10; i++) {
dispatch_async(queue, ^{
NSLog(@"testConcurrent %d %@",i,[NSThread currentThread]);
});
} }
3.串行队列同步任务(不开线程)
- (void)serialQueueSync {
//
// #define DISPATCH_QUEUE_SERIAL NULL 串行队列同步任务(一个线程顺序执行)
dispatch_queue_t queue = dispatch_queue_create("serial",DISPATCH_QUEUE_SERIAL);
for (int i = 0; i< 10; i++) {
dispatch_sync(queue, ^{
NSLog(@"testSerial %d %@",i,[NSThread currentThread]);
});
} }
4.串行队列异步任务(不开线程)
- (void)serialQueueASync {
// #define DISPATCH_QUEUE_SERIAL NULL 串行队列异步任务(一个线程)
dispatch_queue_t queue = dispatch_queue_create("serial",DISPATCH_QUEUE_SERIAL);
for (int i = 0; i< 10; i++) {
dispatch_async(queue, ^{
NSLog(@"testSerial %d %@",i,[NSThread currentThread]);
});
} }
a.全局队列同步任务(不开线程)
- (void)globalQueueSync {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
for (int i = 0; i< 10; i++) {
dispatch_sync(queue, ^{
NSLog(@"global %d %@",i,[NSThread currentThread]);
});
} }
b.全局队列异步任务(开线程)
- (void)globalQueueASync {
// 全局队列异步任务(开线程)
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
for (int i = 0; i< 10; i++) {
dispatch_async(queue, ^{
NSLog(@"global %d %@",i,[NSThread currentThread]);
});
} }
e.g:线程间通信 ---- 使用GCD下载图片
- (void)gcdImageLoad {//开异步任务
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 1 找图片的下载地址
NSString *imageUrlStr1 = @"http://img2.zol.com.cn/product/95/20/ceSFw3e3TqLNM.jpg";
// NSString *imageUrlStr3 = @"http://192.168.1.20/787787.png";
NSURL *url = [NSURL URLWithString:imageUrlStr1];
// 2 苹果的url方法都是同步的 会卡界面
NSData *data = [NSData dataWithContentsOfURL:url]; // 默认的timeOut是60秒
// 3 回主队列更新UI
dispatch_async(dispatch_get_main_queue(), ^{
self.iconImageView.image = [UIImage imageWithData:data];
//执行顺序是132
});
}); }
- (IBAction)testGCDClick:(id)sender {
[self gcdImageLoad]; }
- (IBAction)gcdOperateClick:(id)sender {
dispatch_async(
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 执行耗时的异步操作...
// 图片的下载
NSLog(@"1 imageDownedLoad %@",[NSThread currentThread]);
dispatch_async(dispatch_get_main_queue(), ^{
// 回到主线程,执行UI刷新操作
// 刷新图片信息 执行异步顺序132如果变成sync同步执行顺序123
NSLog(@"3 updateUI");
});
// NSLog(@"2 dfadfadfadf");
})}
- (IBAction)gcdOperateClick:(id)sender {