-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
//创建一个调度组
dispatch_group_t group = dispatch_group_create();
//把任务添加到调度组中 dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
NSLog(@"下载A%@",[NSThread currentThread]); });
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
NSLog(@"下载B%@",[NSThread currentThread]); });
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
NSLog(@"下载C%@",[NSThread currentThread]); });
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
NSLog(@"下载D%@",[NSThread currentThread]); });
//dispatch_group_notify 当调度组里的所有的任务执行完成后, 执行dispatch_group_notify这个函数里写的任务.
dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{ dispatch_group_async(group, dispatch_get_main_queue(), ^{
NSLog(@"在%@中更新UI,提示已下载完成",[NSThread currentThread]); }); });}
打印如下:
2016-07-03 15:59:49.564 调度组的使用[4577:320369] 下载A{number = 3, name = (null)}
2016-07-03 15:59:49.564 调度组的使用[4577:320385] 下载C{number = 5, name = (null)}
2016-07-03 15:59:49.564 调度组的使用[4577:320379] 下载B{number = 2, name = (null)}
2016-07-03 15:59:49.564 调度组的使用[4577:320384] 下载D{number = 4, name = (null)}
2016-07-03 15:59:49.566 调度组的使用[4577:320225] 在{number = 1, name = main}中更新UI,提示已下载完成
一次性执行操作:
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[self once];
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[self once];
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[self once];
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[self once];
});
}
-(void)once{
static dispatch_once_t onceToken;
/**
dispatch_once : 保证block 里面的任务代码只执行一次
参数一 dispatch_once_t token 标识
参数二 要执行的代码任务
*/
dispatch_once(&onceToken, ^{
NSLog(@"一次执行%@",[NSThread currentThread]);
});
NSLog(@"end");
}
网友评论