赞
踩
dispatch_queue_t mainQueue=dispatch_get_main_queue();
同步执行+系统串行队列,会发生死锁。
dispatch_sync(mainQueue, ^{
NSLog(@"%@",[NSThread currentThread]);
});
异步执行+系统串行队列,不开辟子线程,顺序执行。
dispatch_async(mainQueue, ^{
NSLog(@"%@",[NSThread currentThread]);
});
dispatch_queue_t concu=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
同步执行+系统并行队列,不开辟子线程,顺序执行。
dispatch_sync(concu, ^{
NSLog(@"%@",[NSThread currentThread]);
});
异步执行+系统并行队列,开辟子线程,并发执行。
dispatch_async(concu, ^{
NSLog(@"%@",[NSThread currentThread]);
});
dispatch_queue_t queSerial=dispatch_queue_create("jrQueueSerial", DISPATCH_QUEUE_SERIAL);2、创建并行队列
//同步+自创建串行队列,不开辟子线程,顺序执行
dispatch_sync(queSerial, ^{
[NSThread sleepForTimeInterval:2];
NSLog(@"%@",[NSThread currentThread]);
});
//异步+自创建串行队列,开辟子线程,顺序执行
dispatch_async(queSerial, ^{
[NSThread sleepForTimeInterval:2];
NSLog(@"%@",[NSThread currentThread]);
});
dispatch_queue_t queConcu=dispatch_queue_create("jrQueueConcu", DISPATCH_QUEUE_CONCURRENT);
//同步+自创建并行队列不开辟子线程,顺序执行
dispatch_sync(queConcu, ^{
[NSThread sleepForTimeInterval:2];
NSLog(@"%@",[NSThread currentThread]);
});
//异步+自创建并行队列,开辟子线程,并发执行
dispatch_async(queConcu, ^{
[NSThread sleepForTimeInterval:2];
NSLog(@"%@",[NSThread currentThread]);
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{其他:
子线程操作.......
dispatch_sync(dispatch_get_main_queue(), ^{
主线程操作.......
});
});
1、dispatch_group_async的使用2、延迟执行,(在子线程中开启的主线程)不会阻塞主线程
dispatch_queue_t queConcu=dispatch_queue_create("jrQueueConcu", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group=dispatch_group_create();
dispatch_group_async(group, queConcu, ^{
});
//最后执行
dispatch_group_notify(group, queConcu, ^{
});
dispatch_group_async(group, queConcu, ^{
});
dispatch_group_async可以实现监听一组任务是否完成,完成后得到通知dispatch_group_notify(group, queConcu, ^{
})最后执行。
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{3、障碍,会阻塞它后面的线程
NSURL * url=[NSURL URLWithString:path];
NSData * data=[NSData dataWithContentsOfURL:url];
UIImage * image=[UIImage imageWithData:data];
imageView.image=image;
});
dispatch_async(queConcu, ^{4、只运行一次(可用于单例)
NSLog(@"=====0");
});
dispatch_barrier_async(queConcu, ^{
[NSThread sleepForTimeInterval:3];
NSLog(@"障碍");
});
dispatch_async(queConcu, ^{
NSLog(@"=====1");
});
dispatch_async(queConcu, ^{
NSLog(@"=====2");
});
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
});
@implementation Single
//单例
static Single * single;//属于类的,只分配一次内存空间
+(instancetype)shareSingle{
if (single==nil) {
single=[[super allocWithZone:nil]init];
}
// static dispatch_once_t onceToken;
// dispatch_once(&onceToken, ^{
// single=[[super allocWithZone:nil]init];
// });
return single;
//alloc会调用
+(instancetype)allocWithZone:(struct _NSZone *)zone{
return [self shareSingle];
}
-(instancetype)copyWithZone:(struct _NSZone *)zone{
return [Single shareSingle];
//return [[self class] shareSingle];
}
@end
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。