GCD简单使用

来源:互联网 发布:成都网络理政平台 编辑:程序博客网 时间:2024/06/05 10:38

GCD是苹果封装的c语言级别的多线程机制

1. 在主线程上异步执行一段代码

 dispatch_async(dispatch_get_main_queue(), ^{            NSLog(@"%@",[NSThread currentThread]);        });

2. 在主线程上同步执行一段代码

dispatch_sync(dispatch_get_main_queue(), ^{         NSLog(@"%@",[NSThread currentThread]);        });

3.获取主线程缺省的队列

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{        NSLog(@"%@",[NSThread currentThread]);    });        dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)    //此缺省队列在运行的时候由系统来分配管理,如果主线程忙,则系统会自动创建一个新的线程队列。否则就是一个其他的线程队列</span>


4.创建其他线程队列
dispatch_queue_t queue = dispatch_queue_create("other.queue", NULL);  //同步其他线程队列    dispatch_queue_t queue = dispatch_queue_create("other.queue", DISPATCH_QUEUE_SERIAL);   //同步其他线程队列    dispatch_queue_t queue = dispatch_queue_create("other.queue", DISPATCH_QUEUE_CONCURRENT); // 异步其他线程队列</span>    dispatch_async(queue, ^{        NSLog(@"%@",[NSThread currentThread]);    });

 5.异步执行一段代码,执行完成后通知主线程 

dispatch_queue_t queue = dispatch_queue_create("other.queue", DISPATCH_QUEUE_CONCURRENT);    dispatch_async(queue, ^{                // 执行其他处理        NSLog(@"执行其他处理--%@",[NSThread currentThread]);                [NSThread sleepForTimeInterval:2.0];                dispatch_async(dispatch_get_main_queue(), ^{            // 执行完毕            NSLog(@"执行完毕--%@",[NSThread currentThread]);        });    });

6. 延时执行

-(void)afterDelay:(NSTimeInterval )timerInterval block:(void (^)())block{    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timerInterval*NSEC_PER_SEC));    dispatch_after(time, dispatch_get_main_queue(), ^{        block();    });}

0 0