主队列:
#pragma mark 主队列
- (void)mainQueue {
// 获取主队列
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_async(mainQueue, ^{
NSLog(@"1");
});
dispatch_async(mainQueue, ^{
NSLog(@"2");
});
dispatch_async(mainQueue, ^{
NSLog(@"3");
});
}
全局队列:
#pragma mark 全局队列
- (void)globalQueue {
// 获取全局队列
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(globalQueue, ^{
NSLog(@"1");
});
dispatch_async(globalQueue, ^{
NSLog(@"2");
});
dispatch_async(globalQueue, ^{
NSLog(@"3");
});
}
创建一个并行队列:
#pragma mark 创建一个并行队列
- (void)concurrentQueue {
// 创建一个并行队列
dispatch_queue_t concurrentQueue = dispatch_queue_create("com.iosdawei.gcd-dvvdemo", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(concurrentQueue, ^{
NSLog(@"1");
});
dispatch_async(concurrentQueue, ^{
NSLog(@"2");
});
dispatch_async(concurrentQueue, ^{
NSLog(@"3");
});
}
调度组:
#pragma mark 调度组
- (void)dispatchGroup {
// 创建调度组
dispatch_group_t group = dispatch_group_create();
// 获取全局队列
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_async(group, globalQueue, ^{
NSLog(@"1");
});
dispatch_group_async(group, globalQueue, ^{
NSLog(@"2");
});
dispatch_group_async(group, globalQueue, ^{
NSLog(@"3");
});
// 当之前的队列完成之后才执行这里的内容
dispatch_group_notify(group, globalQueue, ^{
NSLog(@"finish!");
});
}
阻塞执行:
#pragma mark 阻塞执行
- (void)dispatchBarrier {
/*
dispatch_barrier_async 作用是在并行队列中,等待前面的并行操作完成
然后执行
dispatch_barrier_async中的操作,(现在就只会执行这一个操作)
执行完 dispatch-barrier中的内容
最后该并行队列恢复原有执行状态,继续并行执行
// 阻塞执行应用在手动创建的队列中,在主队列中会有问题
*/
// 创建一个并行队列
dispatch_queue_t concurrentQueue = dispatch_queue_create("com.iosdawei.gcd-dvvdemo", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(concurrentQueue, ^{
NSLog(@"1");
});
dispatch_async(concurrentQueue, ^{
NSLog(@"2");
});
dispatch_barrier_async(concurrentQueue, ^{
NSLog(@"我上面的异步线程并行执行完,才会执行我,然后再并行执行我下面的异步线程");
});
dispatch_async(concurrentQueue, ^{
NSLog(@"4");
});
dispatch_async(concurrentQueue, ^{
NSLog(@"5");
});
dispatch_async(concurrentQueue, ^{
NSLog(@"6");
});
}
控制代码只执行一次(例如单例):
#pragma mark 控制代码只执行一次(例如单利)
- (void)dispatchOnce {
// 控制代码只执行一次
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSLog(@"dispatch_once");
});
}
延时执行:
#pragma mark 延时执行
- (void)dispatchAfter {
// 延时执行
NSUInteger second = 3; // 延迟的秒数
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, second * NSEC_PER_SEC);
dispatch_after(time, dispatch_get_global_queue(0, 0), ^{
NSLog(@"dispatch_after");
});
}
重复执行一段代码:
#pragma mark 重复执行一段代码
- (void)dispatchApply {
NSUInteger count = 5; // 重复的次数
dispatch_apply(count, dispatch_get_global_queue(0, 0), ^(size_t i) {
NSLog(@"%lu",i);
});
}