GCD
//1.用异步函数,往全局并发队列添加任务。异步并发开辟新线程同时运行
//2.用同步函数往全局并发队列中添加任务。同步并发在同一个线程中同时运行
//3.用同步函数往串行队列中添加任务。同步串行在同一个线程中一个一个运行任务
//4.用异步函数往串行队中添加任务。异步串行开辟另一条线程一个一个运行任务(只另外开辟一条)
//5.用异步函数往主队列中添加任务。主队列异步串行
//获取主队列
dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_async(queue, ^{
NSLog(@"下载1---- %@",[NSThread currentThread]);
});
//总结:放在主队列中的任务,都在主线程中串行执行,分线程管回调
//6.在主线程中用同步函数往主队列中添加任务,主队列同步,卡死无输出
//总结:在主线程中用同步函数往主队列中添加任务,会造成主线程死锁,下面的代码不会执行
//在分线程中用同步函数往主队列中添加任务---不会造成死锁
[self performSelectorInBackground:@selector(cast6) withObject:nil];
//获取主队列
dispatch_queue_t queue =dispatch_get_main_queue();
//获取全局并发队列
dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//获取全局串行队列
//1.队列的名字(方便测试) 2.队列的属性,一般为NULL
dispatch_queue_t queue =dispatch_queue_create("123456",NULL);
//异步
//把右边的操作(block)交个左边的队列(queue)
dispatch_async(queue, ^{
//添加任务
NSLog(@"下载1---- %@",[NSThread currentThread]);
});
//同步
//把右边的操作(block)交个左边的队列(queue)
dispatch_sync(queue, ^{
//添加任务
NSLog(@"下载1---- %@",[NSThread currentThread]);
});
//回到主线程刷新UI
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"currentThread ---- %@",[NSThread currentThread]);
self.image1.image= image;
});
//优点:分线程中得到的数据,可以直接使用,不需要传值,更加方便和直接
//延迟函数
//1.NSObjiect的延迟方法
NSLog(@"111111.currentThread --- %@",[NSThread currentThread]);
[self performSelector:@selector(run) withObject:nil afterDelay:2.0];
//2.GCD
//什么时间在哪个队列中执行什么方法
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (2.0 *NSEC_PER_SEC)),dispatch_get_main_queue(), ^{
NSLog(@"1.currentThread --- %@",[NSThreadcurrentThread]);
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (2.0 *NSEC_PER_SEC)),dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"3.currentThread --- %@",[NSThread currentThread]);
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (2.0 *NSEC_PER_SEC)),dispatch_queue_create("123",NULL), ^{
NSLog(@"2.currentThread --- %@",[NSThread currentThread]);
});
}
- (void)run{
NSLog(@"0.currentThread --- %@",[NSThread currentThread]);
}
//dispatch_once函数中的操作只执行一次单列类
for(int i = 0; i < 20;i ++) {
__block int count = 0;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
count ++;
NSLog(@"我执行了%d次",count);
});
}