GCD是大家在IOS开发过程中经常使用的一种多线程管理机制。原理这里就不多说了,大家关心的大部分都是它的使用,下面主要介绍GCD的主要方法及其实例。
1.认识主队列,感受串行队列的运行,运行结果打印的是 1,2,3,4,顺序执行。
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_async(mainQueue, ^{
NSLog(@"");
});
dispatch_async(mainQueue, ^{
NSLog(@"");
});
dispatch_async(mainQueue, ^{
NSLog(@"");
});
dispatch_async(mainQueue, ^{
NSLog(@"");
});
2.认识全局队列,体验并发队列的运行,运行结果随机打印:2,3,1,4,随机执行。
dispatch_queue_t defaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, );
dispatch_async(defaultQueue, ^{
NSLog(@"");
});
dispatch_async(defaultQueue, ^{
NSLog(@"");
});
dispatch_async(defaultQueue, ^{
NSLog(@"");
});
dispatch_async(defaultQueue, ^{
NSLog(@"");
});
3.创建自定义队列
dispatch_queue_t concurrentQueue = dispatch_queue_create("com.bjsxt.concurrentQueue", DISPATCH_QUEUE_CONCURRENT); dispatch_async(concurrentQueue, ^{
NSLog(@"");
dispatch_sync(concurrentQueue, ^{
[NSThread sleepForTimeInterval:];
NSLog(@"");
});
NSLog(@"");
});
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, );
dispatch_group_async(group, defaultQueue, ^{
[NSThread sleepForTimeInterval:];
NSLog(@"");
});
dispatch_group_async(group, defaultQueue, ^{
[NSThread sleepForTimeInterval:];
NSLog(@"");
});
dispatch_group_notify(group, defaultQueue, ^{
NSLog(@"");
});
7.dispatch_barrier_async 在前面的任务执行结束后它才执行,而且它后面的任务等它执行完成之后才会执行.
dispatch_queue_t queue = dispatch_queue_create("com.bjsxt.barrierExecute", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
[NSThread sleepForTimeInterval:];
NSLog(@"");
});
dispatch_async(queue, ^{
[NSThread sleepForTimeInterval:];
NSLog(@"");
});
dispatch_barrier_async(queue, ^{
NSLog(@"");
[NSThread sleepForTimeInterval:]; });
dispatch_async(queue, ^{
[NSThread sleepForTimeInterval:];
NSLog(@"");
});
8.执行某个代码dispatch_apply
dispatch_queue_t defaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, );
dispatch_apply(, defaultQueue, ^(size_t i) {
NSLog(@"%lu",i);
});