您的位置:首页 > 其它

多线程:GCD 基本使用

2016-03-25 23:22 281 查看
//
//  ViewController.m
//  05-GCD基本使用
//
//  Created by gzxzmac on 16/1/29.
//  Copyright © 2016年 gzxzmac. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self gcdDemo3];
}
/**
跟NSThread 对比

1. GCD使用block ,代码都放在一起,比较直观。NSThread 需要使用selector 来指定线程入口
2. GCD 回到主线程使用 dispatch_get_main_queue .NSThread 回到主线程,只能通过NSObject 的分类方法来实现

*/

// 同步
- (void)gcdDemo {
// 同步
// 任务
void (^task)() = ^ {
NSLog(@"%@",[NSThread currentThread]);
};

dispatch_sync(dispatch_get_global_queue(0, 0), task);
}

//异步
- (void)gcdDemo1 {
void (^task)() = ^ {
NSLog(@"%@",[NSThread currentThread]);
};
dispatch_async(dispatch_get_global_queue(0, 0), task);
}

// 精简
- (void)gcdDemo2 {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"%@",[NSThread currentThread]);
});
}

// 线程间通讯
- (void)gcdDemo3 {
// 下载
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"正在下载%@",[NSThread currentThread]);
// 回到主线程刷新UI
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(@"刷新UI%@",[NSThread currentThread]);
});
});
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: