延遲執(zhí)行
//第一個參數(shù):dispatch_time_t when 時間
//第二個參數(shù):dispatch_queue_t queue 隊列
//第三個參數(shù):dispatch_block_t block 執(zhí)行的block
//這段代碼的含義為:讓主隊列延遲兩秒打印LitterL
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"LitterL");
});
一次性執(zhí)行
//第一個參數(shù):dispatch_once_t *predicate 記錄代碼是否被執(zhí)行過 默認(rèn)為0 但執(zhí)行一次后就是-1了 所以就看到智能執(zhí)行一次的這個效果
//第二個參數(shù):dispatch_block_t block 執(zhí)行的block
_dispatch_once(dispatch_once_t *predicate, dispatch_block_t block)
{
if (DISPATCH_EXPECT(*predicate, ~0l) != ~0l) {
dispatch_once(predicate, block);
}
}
//-------------------實例---------------------
-(void)once
{
//整個程序運行過程中只會執(zhí)行一次
//onceToken用來記錄該部分的代碼是否被執(zhí)行過
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSLog(@"LitterL");
});
}
柵欄函數(shù)(控制任務(wù)的執(zhí)行順序)
//柵欄函數(shù)
//第一個參數(shù) dispatch_queue_t 隊列
//第二個參數(shù) dispatch_block_t 執(zhí)行的block
//作用:在我們需要控制任務(wù)的順序的時候可以使用柵欄函數(shù),進行控制
dispatch_async(dispatch_queue_t queue, dispatch_block_t block);
//-------------------------實例---------------------------
//
// 不管怎么輸出斥难,我的1-X伟姐、2-X都是在上面坦仍,而不是隨意亂輸出
//
-(void)barrier
{
//1.獲得隊列
dispatch_queue_t queue = dispatch_queue_create("download", DISPATCH_QUEUE_CONCURRENT);
//2.異步函數(shù)
dispatch_async(queue, ^{
for (NSInteger i =0; i<10; i++) {
NSLog(@"1-%zd--%@",i,[NSThread currentThread]);
}
});
dispatch_async(queue, ^{
for (NSInteger i =0; i<10; i++) {
NSLog(@"2-%zd--%@",i,[NSThread currentThread]);
}
});
//柵欄函數(shù):控制并發(fā)隊列中任務(wù)的執(zhí)行順序
dispatch_barrier_async(queue, ^{
NSLog(@"+++++++++++++++++++++++++++");
});
dispatch_async(queue, ^{
for (NSInteger i =0; i<10; i++) {
NSLog(@"3-%zd--%@",i,[NSThread currentThread]);
}
});
dispatch_async(queue, ^{
for (NSInteger i =0; i<10; i++) {
NSLog(@"4-%zd--%@",i,[NSThread currentThread]);
}
});
}
快速迭代
-(void)test
{
//1.獲得并發(fā)隊列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//2.快速迭代
/*
第一個參數(shù):要迭代的次數(shù)
第二個參數(shù):隊列,并發(fā)隊列
第三個參數(shù):block 封裝任務(wù)
*/
dispatch_apply(10, queue, ^(size_t index) {
NSLog(@"%zd----%@",index,[NSThread currentThread]);
});
}
隊列組
-(void)group
{
//0.創(chuàng)建隊列組
dispatch_group_t group = dispatch_group_create();
//1.創(chuàng)建隊列
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
//2.異步函數(shù)
/*
1)封裝任務(wù)
2)把任務(wù)添加到隊列中
3)監(jiān)聽任務(wù)的執(zhí)行情況,group
*/
dispatch_group_async(group, queue, ^{
NSLog(@"download1---%@",[NSThread currentThread]);
});
dispatch_group_async(group, queue, ^{
NSLog(@"download2---%@",[NSThread currentThread]);
});
dispatch_group_async(group, queue, ^{
NSLog(@"download3---%@",[NSThread currentThread]);
});
//3.當(dāng)隊列組中所有的任務(wù)都執(zhí)行完畢之后會通知group執(zhí)行dispatch_group_notify方法
dispatch_group_notify(group, queue, ^{
NSLog(@"隊列組中所有的任務(wù)都執(zhí)行完畢了");
});
}
結(jié)束
本章到此結(jié)束
歡迎各位碼友隨意轉(zhuǎn)載并指正