直接贴出常用的函数,方便要用的时候直接使用。
------------- type 1 ----------------
说明 :
创建一个dispatch_group_t,每次网络请求前先dispatch_group_enter,请求回调后再dispatch_group_leave,对于enter和leave必须配合使用,有几次enter就要有几次leave,否则group会一直存在。当所有enter的group都leave后,会执行dispatch_group_notify的block
dispatch_group_t downLoadGroup = dispatch_group_create(); dispatch_group_enter(downLoadGroup); dispatch_group_leave(downLoadGroup); dispatch_group_notify(downLoadGroup, dispatch_get_main_queue(), ^{ NSLog(@"回到主线程通知"); });
------------- type 2 ----------------
说明 :
延迟方法
double delayInSeconds = 3; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ NSLog(@"主线程中延迟方法执行回调"); });
------------- type 3 ----------------
说明 :
等待之前的线程结束(会阻塞线程,慎用)
dispatch_group_t waitGroup = dispatch_group_create(); dispatch_group_wait(waitGroup, DISPATCH_TIME_FOREVER);
------------- type 4 ----------------
说明 :
开启异步线程 --
会创建group 在所有线程执行完成之后会执行notify block 注意:notify要放在最后。
dispatch_group_t group = dispatch_group_create(); dispatch_queue_t queue = dispatch_queue_create("com.gcd-group.www", DISPATCH_QUEUE_CONCURRENT); dispatch_group_async(group, queue, ^{ for (int i = 0; i < 1000000000; i++) { if (i == 999999999) { NSLog(@"11111111"); } } }); dispatch_group_async(group, queue, ^{ NSLog(@"22222222"); }); dispatch_group_async(group, queue, ^{ NSLog(@"33333333"); }); dispatch_group_notify(group, queue, ^{ NSLog(@"done"); });
------------- type 5 ----------------
说明 :
开启异步线程
dispatch_queue_t concurrentDiapatchQueue=dispatch_queue_create("com.test.queue", DISPATCH_QUEUE_CONCURRENT); dispatch_async(concurrentDiapatchQueue, ^{ NSLog(@"1"); }); dispatch_async(concurrentDiapatchQueue, ^{ sleep(2); NSLog(@"2"); }); dispatch_async(concurrentDiapatchQueue, ^{ sleep(1); NSLog(@"3"); });
------------- type 6 ----------------
说明 :
开启同步线程
dispatch_queue_t serialDiapatchQueue=dispatch_queue_create("com.test.queue", DISPATCH_QUEUE_SERIAL); dispatch_async(serialDiapatchQueue, ^{ NSLog(@"1"); }); dispatch_async(serialDiapatchQueue, ^{ NSLog(@"2"); sleep(2); NSLog(@"2-------"); }); dispatch_async(serialDiapatchQueue, ^{ NSLog(@"3"); sleep(2); NSLog(@"3--------"); });
------------- type 7 ----------------
说明 :
GCD的栅栏方法 dispatch_barrier_async
dispatch_queue_t queue = dispatch_queue_create("12312312", DISPATCH_QUEUE_CONCURRENT); dispatch_async(queue, ^{ NSLog(@"----1---"); }); dispatch_async(queue, ^{ NSLog(@"----2----"); }); dispatch_barrier_async(queue, ^{ NSLog(@"----barrier----"); }); dispatch_async(queue, ^{ NSLog(@"----3-----"); }); dispatch_async(queue, ^{ NSLog(@"----4-----"); }); dispatch_async(queue, ^{ NSLog(@"----5-----"); }); dispatch_async(queue, ^{ NSLog(@"----6-----"); });
多线程的链接:http://www.cocoachina.com/ios/20170707/19769.html