GCD常用的函数
1、延迟函数
//延迟执行
//[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(task) userInfo:nil repeats:YES];
//[self performSelector:@selector(task) withObject:nil afterDelay:3.0];
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
//GCD延迟执行
/*
第一个参数:表示从什么时候开始计时 DISPATCH_TIME_NOW:现在
第二个参数:间隔的时间
第三个参数:队列,决定block在哪个线程中调用,只有当队列是主队列的时候才在主线程调用
第四个参数:
*/
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), queue, ^{
NSLog(@"----GCD---%@",[NSThread currentThread]);
});
2、栅栏函数
//1.创建并发队列
dispatch_queue_t queue = dispatch_queue_create("www.yifuj.com", DISPATCH_QUEUE_CONCURRENT);
//2.使用异步函数添加任务
dispatch_async(queue, ^{
for (NSInteger i = 0; i<10; i++) {
NSLog(@"download 1--%zd-%@",i,[NSThread currentThread]);
}
});
dispatch_async(queue, ^{
for (NSInteger i = 0; i<10; i++) {
NSLog(@"download 2--%zd-%@",i,[NSThread currentThread]);
}
});
dispatch_async(queue, ^{
for (NSInteger i = 0; i<10; i++) {
NSLog(@"download 3--%zd-%@",i,[NSThread currentThread]);
}
});
//栅栏函数:控制队列中任务的执行顺序,前面的所有任务执行完毕之后执行栅栏函数,自己执行完毕之后再之后后面的任务
dispatch_barrier_async(queue, ^{
NSLog(@"++++++++++++++++++++++++++");
});
dispatch_async(queue, ^{
for (NSInteger i = 0; i<10; i++) {
NSLog(@"download 4--%zd-%@",i,[NSThread currentThread]);
}
});
dispatch_async(queue, ^{
for (NSInteger i = 0; i<10; i++) {
NSLog(@"download 5--%zd-%@",i,[NSThread currentThread]);
}
});