-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{? ??
//創(chuàng)建一個(gè)調(diào)度組? ?
dispatch_group_t group = dispatch_group_create();? ??
//把任務(wù)添加到調(diào)度組中? ? 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 當(dāng)調(diào)度組里的所有的任務(wù)執(zhí)行完成后, 執(zhí)行dispatch_group_notify這個(gè)函數(shù)里寫的任務(wù).? ??
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 調(diào)度組的使用[4577:320369] 下載A{number = 3, name = (null)}
2016-07-03 15:59:49.564 調(diào)度組的使用[4577:320385] 下載C{number = 5, name = (null)}
2016-07-03 15:59:49.564 調(diào)度組的使用[4577:320379] 下載B{number = 2, name = (null)}
2016-07-03 15:59:49.564 調(diào)度組的使用[4577:320384] 下載D{number = 4, name = (null)}
2016-07-03 15:59:49.566 調(diào)度組的使用[4577:320225] 在{number = 1, name = main}中更新UI,提示已下載完成
一次性執(zhí)行操作:
-(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 里面的任務(wù)代碼只執(zhí)行一次
參數(shù)一? dispatch_once_t? token? 標(biāo)識(shí)
參數(shù)二? 要執(zhí)行的代碼任務(wù)
*/
dispatch_once(&onceToken, ^{
NSLog(@"一次執(zhí)行%@",[NSThread currentThread]);
});
NSLog(@"end");
}