GCD是大家在IOS开发过程中经常使用的一种多线程管理机制。原理这里就不多说了,大家关心的大部分都是它的使用,下面主要介绍GCD的主要方法及其实例。
1.认识主队列,感受串行队列的运行,运行结果打印的是 1,2,3,4,顺序执行。
dispatch_queue_t mainQueue = dispatch_get_main_queue(); dispatch_async(mainQueue, ^{ NSLog(@"1"); }); dispatch_async(mainQueue, ^{ NSLog(@"2"); }); dispatch_async(mainQueue, ^{ NSLog(@"3"); }); dispatch_async(mainQueue, ^{ NSLog(@"4"); });
2.认识全局队列,体验并发队列的运行,运行结果随机打印:2,3,1,4,随机执行。
dispatch_queue_t defaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(defaultQueue, ^{ NSLog(@"1"); }); dispatch_async(defaultQueue, ^{ NSLog(@"2"); }); dispatch_async(defaultQueue, ^{ NSLog(@"3"); }); dispatch_async(defaultQueue, ^{ NSLog(@"4"); });
3.创建自定义队列
dispatch_queue_t concurrentQueue = dispatch_queue_create("com.bjsxt.concurrentQueue", DISPATCH_QUEUE_CONCURRENT); dispatch_async(concurrentQueue, ^{ NSLog(@"4"); dispatch_sync(concurrentQueue, ^{ [NSThread sleepForTimeInterval:3]; NSLog(@"5"); }); NSLog(@"6"); });
4.GCD在单例中的运用dispatch_once
static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ NSLog(@"onceToken"); });
5.延迟加载dispatch_after
double delayInSeconds = 2.0; dispatch_queue_t mainQueue = dispatch_get_main_queue(); dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW,delayInSeconds * NSEC_PER_SEC); dispatch_after(popTime, mainQueue, ^{ NSLog(@"延时执行的2秒"); });
6.调度组dispatch_group_t
dispatch_group_t group = dispatch_group_create(); dispatch_queue_t defaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_group_async(group, defaultQueue, ^{ [NSThread sleepForTimeInterval:3]; NSLog(@"1"); }); dispatch_group_async(group, defaultQueue, ^{ [NSThread sleepForTimeInterval:2]; NSLog(@"2"); }); dispatch_group_notify(group, defaultQueue, ^{ NSLog(@"3"); });
7.dispatch_barrier_async 在前面的任务执行结束后它才执行,而且它后面的任务等它执行完成之后才会执行.
dispatch_queue_t queue = dispatch_queue_create("com.bjsxt.barrierExecute", DISPATCH_QUEUE_CONCURRENT); dispatch_async(queue, ^{ [NSThread sleepForTimeInterval:2]; NSLog(@"1"); }); dispatch_async(queue, ^{ [NSThread sleepForTimeInterval:4]; NSLog(@"2"); }); dispatch_barrier_async(queue, ^{ NSLog(@"3"); [NSThread sleepForTimeInterval:4]; }); dispatch_async(queue, ^{ [NSThread sleepForTimeInterval:1]; NSLog(@"4"); });
8.执行某个代码dispatch_apply
dispatch_queue_t defaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_apply(5, defaultQueue, ^(size_t i) { NSLog(@"%lu",i); });