調(diào)度組,一次性執(zhí)行操作的使用

-(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");

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容