经常要用的,总结分类一下。
//获得队列 DISPATCH_QUEUE_PRIORTY 优先级 dispatch_queue_t Queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0); dispatch_queue_t MainQueue = dispatch_get_main_queue(); //自定义Queue 第二参数默认串行(FIFO) DISPATCH_QUEUE_CONCURRENT(可选,并发) dispatch_queue_t SelfQueue = dispatch_queue_create("COM.M1989.Queue", NULL); //dispatch_async dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{ //Do Some? }); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{ //耗时操作 dispatch_async(dispatch_get_main_queue(), ^{ //更新界面 }); }); //dispatch_once_t 单例模式常用 static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ }); // dispatch_apply 并行,可利用CPU多核进行多线程操作 不过会阻塞当前线程, dispatch_apply(10, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t y) { NSLog(@"123,%zu",y); }); //觉得还是反正子线程比较好。如下 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{ dispatch_apply(10, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t y) { NSLog(@"123,%zu",y); }); }); //dispatch_after 延迟执行,缺点不能临时取消,起码NSTimer 有个-(void)invalidate 能取消 double Seconds = 10.0; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (Seconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^(void){ //延后10秒需要执行的代码 }); //dispatch_group_t 并行 group全部完成后发消息给notify,执行notify里block内容。 不阻塞当前线程。。。。 dispatch_group_t groupQ = dispatch_group_create(); dispatch_group_async(groupQ, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSLog(@"1"); }); dispatch_group_async(groupQ, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSLog(@"2"); }); dispatch_group_async(groupQ, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ for(int i = 0;i<10000;i++){ NSLog(@"3"); } }); dispatch_group_notify(groupQ, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSLog(@"OK"); }); //dispatch_barrier_async 等待前面所有的任务执行完,并中断在此之后的任务。当前面的任务执行完后,此会执行,并恢复后面的任务。(试了,结果不理想) dispatch_barrier_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSLog(@"barrier"); });
未完待续。。。
来源:https://www.cnblogs.com/ngi8/p/5096581.html