GCD之队列的选择和与主线程之间的通信

来源:互联网 发布:maya编程语言 编辑:程序博客网 时间:2024/05/23 11:53
队列的选择:
串行队列异步执行

- 开一条线程, 顺序执行。
- 效率:不高,执行比较慢,资源占用小,省电。
适用于网络连接:一般网络是3G,对性能要求不是很高。
并发队列异步执行:
- 开启多条线程,并发执行。
- 效率:高,执行快,资源消耗大,费电。
适用场合:
适用于网络WiFi,或者需要很快的响应,要求用户体验非常流畅。对任务执行顺序没有要求。

-同步任务:一般只会在并发队列,需要阻塞后续任务。必须等待同步任务执行完毕,再去执行其他任务。”依赖”关系。

代码运行如下:

////  ViewController.m//  备课代码05-显示网络图片(线程间通信)////  Created by 刘天源 on 15/1/8.//  Copyright (c) 2015年 itheima. All rights reserved.//#import "ViewController.h"@interface ViewController () <UIScrollViewDelegate>@property (strong, nonatomic)  UIImageView *iconView;@end@implementation ViewController-(void)viewDidLoad{    self.iconView = [[UIImageView alloc] initWithFrame:self.view.bounds];    [self.view addSubview:self.iconView];}- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {    dispatch_async(dispatch_get_global_queue(0, 0), ^{        NSLog(@"%@", [NSThread currentThread]);        // 耗时操作放在全局队列,异步执行        // 1. url确定一个网络上的资源路径         NSURL *url = [NSURL URLWithString:@"http://g.hiphotos.baidu.com/image/pic/item/b8014a90f603738def2887edb11bb051f919ec9b.jpg"];                //  2. 通过URL可以下载对应的网络资源,网络资源传输的都是二进制        NSData *data = [NSData dataWithContentsOfURL:url];                // 3. 二进制数据转成图片        UIImage *image = [UIImage imageWithData:data];                // 4. 更新UI  在主线程 只要把任务添加到主队列,就会载主队列执行。        dispatch_async(dispatch_get_main_queue(), ^{            self.iconView.image = image;            NSLog(@"%@", [NSThread currentThread]);        });    });//  注意:同步执行主队列任务的操作只会由当前主线程调度时才会发生死锁,放在异步任务中就会有别的线程而不是当前主线程进行调度,就不会发生死锁。//    dispatch_sync(dispatch_get_main_queue(), ^{//        NSLog(@"设置完成");//    });}@end
运行结果如下:



0 0
原创粉丝点击