//1.同步顺序执行
- (void)test1
{
dispatch_async(mainQueue, ^{
[selfdoSomeThing:@"A"];
});
dispatch_async(mainQueue, ^{
[selfdoSomeThing:@"B"];
});
dispatch_async(mainQueue, ^{
[selfdoSomeThing:@"C"];
});
}
//2.异步同时进行
- (void)test2
{
dispatch_async(globalQueue, ^{
[selfdoSomeThing:@"A"];
});
dispatch_async(globalQueue, ^{
[selfdoSomeThing:@"B"];
});
dispatch_async(globalQueue, ^{
[selfdoSomeThing:@"C"];
});
}
//3.A B同时进行最后执行C
- (void)test3
{
dispatch_group_tgroup =dispatch_group_create();
dispatch_group_async(group,globalQueue, ^{
[selfdoSomeThing:@"A"];
});
dispatch_group_async(group,globalQueue, ^{
[selfdoSomeThing:@"B"];
});
dispatch_group_async(group,globalQueue, ^{
[selfdoSomeThing:@"C"];
});
dispatch_group_async(group,globalQueue, ^{
[selfdoSomeThing:@"D"];
});
dispatch_group_notify(group,globalQueue, ^{
[selfdoSomeThing:[NSStringstringWithFormat:@"最后执行----%d",[NSThreadisMainThread]]];
dispatch_async(mainQueue, ^{
[selfdoSomeThing:[NSStringstringWithFormat:@"主线程刷新UI----%d",[NSThreadisMainThread]]];
});
});
}
//4.自定义队列自定义执行顺序可串行可并行
- (void)test4
{
dispatch_queue_tcustomQueue =dispatch_queue_create("anfu",DISPATCH_QUEUE_CONCURRENT);
dispatch_async(customQueue, ^{
[selfdoSomeThing:@"A"];
});
dispatch_async(customQueue, ^{
[selfdoSomeThing:@"B"];
});
dispatch_barrier_async(customQueue, ^{
[selfdoSomeThing:@"C"];
});
dispatch_async(customQueue, ^{
[selfdoSomeThing:@"D"];
});
dispatch_async(customQueue, ^{
[selfdoSomeThing:@"E"];
});
}
//5.延迟调用
- (void)test5
{
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1*NSEC_PER_SEC)),dispatch_get_main_queue(), ^{
[selfdoSomeThing:@"过1秒后执行"];
});
}
//6.调用多次
- (void)test6
{
dispatch_apply(10,globalQueue, ^(size_ttime) {
NSLog(@"%zu",time);
});
}
//7.只调用一次,一般在单例中使用
- (void)test7
{
staticdispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
NSLog(@"只调用一次");
});
}
//公共调用方法
- (void)doSomeThing:(NSString*)obj
{
sleep(1);
NSLog(@"%@",obj);
}