GCD常用函数
// ViewController.m
// 4.16-GCD常用函数
//
// Created by 裴铎 on 2018/4/16.
// Copyright © 2018年 裴铎. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self once];
}
/** 延期函数 */
- (void)delay{
//为例验证 打印开始时间
NSLog(@"start");
//1./延时执行的方法
[self performSelector:@selector(task) withObject:nil afterDelay:2.0];
//2./延时执行的方法 最后一个参数是:是否重复
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(task) userInfo:nil repeats:NO];
//3./延时执行的方法GCD
//dispatch_queue_t queue = dispatch_get_main_queue();
//获取全局并发队列 默认的优先级
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
/**
参数
1./重什么时间开始延迟 DISPATCH_TIME_NOW现在 DISPATCH_TIME_FOREVER未来
2./延迟多少时间(delayInSeconds) 填写秒数 * 1000000000纳秒(NSEC_PER_SEC)GCD中时间是以纳秒计算
3./在哪一个队列中执行 dispatch_get_main_queue() 可以是子线程 这个是别的方法没有的
4./填写要执行的任务
想让延迟任务在子线程中执行只传入一个并发队列就可以了
*/
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), queue, ^{
//在这个block中写要执行的任务
NSLog(@"当前线程:%@ 任务:%s",[NSThread currentThread],__func__);
});
}
/** 一次性代码
整个应用程序的生命周期中只会执行一次的
一次性带么不能放在懒加载中使用,用了你第二次取值时就为空了
一次性代码主要用在单利模式中 并且 是检查线程安全的(原子性)*/
- (void)once{
NSLog(@"%s",__func__);
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSLog(@"__once__");
});
}
/** 任务 */
- (void)task{
NSLog(@"当前线程:%@ 任务:%s",[NSThread currentThread],__func__);
}
@end
GCD栅栏函数
// ViewController.m
// 4.16-GCD栅栏函数
//
// Created by 裴铎 on 2018/4/16.
// Copyright © 2018年 裴铎. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//获得一个默认优先级的全局并发队列
//dispatch_queue_t queue = dispatch_get_global_queue(0, 0 );
//如果有栅栏函数的话必须使用自己创建的并发队列
dispatch_queue_t queue = dispatch_queue_create("peiDuo", DISPATCH_QUEUE_CONCURRENT);
//创建异步函数
dispatch_async(queue, ^{
NSLog(@" 任务1:%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@" 任务2:%@",[NSThread currentThread]);
});
//创建一个栅栏函数 栅栏函数之前的任务并发执行,完成后执行栅栏任务,完成后并发执行栅栏函数之后的任务
dispatch_barrier_async(queue, ^{
NSLog(@" ++++++++++++++++ 这是一个栅栏 +++++++++++++++");
});
dispatch_async(queue, ^{
NSLog(@" 任务3:%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@" 任务4:%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@" 任务5:%@",[NSThread currentThread]);
});
}
@end
网友评论