iOS 【Multithreading-GCD 延时执行操作】

来源:互联网 发布:overture mac注册码 编辑:程序博客网 时间:2024/04/29 04:01
////  ViewController.m//  40-GCD 延迟执行(4)(掌握)//#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 demo4];}- (void)download:(NSString *)url{    NSLog(@"-----download:-----%@",[NSThread currentThread]);}// 这种方法会卡住当前线程并等待时间结束后- (void)demo1{    NSLog(@"----touchesBegan111-----");        [NSThread sleepForTimeInterval:3];        NSLog(@"----touchesBegan222-----");}// 这种方法不会卡住当前线程,而是继续向下执行,等到时间结束的时候再返回到当前线程中执行(缺点:只能返回到当前线程接着进行,而没有办法开启新线程)- (void)demo2{    NSLog(@"----touchesBegan111-----");        [self performSelector:@selector(download:) withObject:@"http://222222.jpg" afterDelay:3];        NSLog(@"----touchesBegan222-----");}// 这是GCD提供的延时方法,这是将主队列传进去,延时过后block内的操作还是在主线程中执行,没有开启新的线程,也不会耽误当前操作(不会卡住线程)。和demo2很相似- (void)demo3{    NSLog(@"----touchesBegan111-----");    NSLog(@"----%@----",[NSThread currentThread]);        dispatch_queue_t queue = dispatch_get_main_queue(); // 可以先初始化好队列,然后将变量名传进去    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), queue, ^{        NSLog(@"主队列 延迟");        NSLog(@"----%@----",[NSThread currentThread]);    });        NSLog(@"----touchesBegan222-----");}// 这也是GCD提供的延时方法,这是将 全局并行队列/串行队列 传进去,延时过后开启新的线程,block内的操作在新线程内执行// 这里一定要注意,传 并行队列 或者 串行队列 都是会开启新线程的     注意:!!!!     GCD 延迟执行的本质!!!     延迟执行 == 延迟提交     A 先把任务提交到队列,然后3秒之后再执行该任务  错误     B 先等3秒的时间,然后再把任务提交到队列  正确- (void)demo4{    NSLog(@"----touchesBegan111-----");    NSLog(@"----%@----",[NSThread currentThread]);    //    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // 可以在方法内部初始化队列,和demo3不同//        //        NSLog(@"全局并发队列 延迟");//        NSLog(@"----%@----",[NSThread currentThread]);//        //    });        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_queue_create("name", NULL), ^{                NSLog(@"串行队列队列 延迟");                NSLog(@"----%@----",[NSThread currentThread]);    });        NSLog(@"----touchesBegan222-----");}@end

2 0
原创粉丝点击