1.一次性执行(单例)
+(SingletonExample *)sharedInstance
{
static SingletonExample *sharedSingleton = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^(void) {
sharedSingleton = [[self alloc] initialize];
});
return sharedSingleton;
}
2.按照一定顺序去执行 同步
- (void)demo
{
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
//异步去执行
dispatch_sync(queue, ^{
NSLog(@"登陆 ---- %@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"付费 ---- %@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"下载 ---- %@",[NSThread currentThread]);
});
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"通知用户 ---- %@",[NSThread currentThread]);
});
});
}
3.线程组的使用 模拟需求:要异步去下载3张图片,全部下载完成后通知用户
- (void)download3Image
{
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_group_async(group, queue, ^{
[NSThread sleepForTimeInterval:2.0];
NSLog(@"下载图片1 %@",[NSThread currentThread]);
});
dispatch_group_async(group, queue, ^{
[NSThread sleepForTimeInterval:1.0];
NSLog(@"下载图片2 %@",[NSThread currentThread]);
});
dispatch_group_async(group, queue, ^{
[NSThread sleepForTimeInterval:2.5];
NSLog(@"下载图片3 %@",[NSThread currentThread]);
});
//
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
NSLog(@"完成啦");
}
4.延迟操作
- (void)gcdDemo
{
//dispatch_after 参数 1.延迟的时间 2.执行的队列 3.执行的任务
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 2.0);
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
void (^task)() = ^{
NSLog(@"%@",[NSThread currentThread]);
};
dispatch_after(time, queue, task);
}
5.线程通讯
- (void)gcdDemo3
{
//线程通信
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"拼命加载中,%@",[NSThread currentThread]);
//[NSThread sleepForTimeInterval:2.0];
dispatch_async(dispatch_get_main_queue(), ^{
//在主线程中更新UI数据
NSLog(@"在主线程中更新UI %@",[NSThread currentThread]);
});
});
}