1 - (void)GCDMethed{ 2 // 后台执行 3 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ 4 5 // 后台执行的操作 6 NSLog(@"后台操作"); 7 }); 8 9 // 主线程执行 10 dispatch_async(dispatch_get_main_queue(), ^{ 11 12 // 主线程执行的操作 13 NSLog(@"主线程操作"); 14 }); 15 16 17 // 一次性执行 18 for (int i=0; i<2; i++) { 19 static dispatch_once_t onceToken; 20 dispatch_once(&onceToken, ^{ 21 // 代码执行一次 22 NSLog(@"代码执行一次"); 23 }); 24 } 25 26 // 延迟2秒执行 27 double delayInSeconds = 2.0; 28 dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); 29 dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ 30 NSLog(@"延迟了2秒执行"); 31 }); 32 33 // 自定义 dispatch_queue_t 34 dispatch_queue_t urls_queue = dispatch_queue_create("blog.devtang.com", NULL); 35 dispatch_queue_t urls_queue2 = dispatch_queue_create("TEST",DISPATCH_QUEUE_CONCURRENT); // 并行的队列 DISPATCH_QUEUE_SERIAL 穿行队列 36 dispatch_async(urls_queue, ^{ 37 38 }); 39 // dispatch_release(urls_queue); ARC 不需要 40 41 42 // 合并汇总结果 43 44 dispatch_group_t group = dispatch_group_create(); 45 dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{ 46 // 并行执行的线程一 47 }); 48 dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{ 49 // 并行执行的线程二 50 }); 51 dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{ 52 // 汇总结果 53 }); 54 55 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 56 57 dispatch_async(dispatch_get_main_queue(), ^{ 58 59 }); 60 }); 61 62 }
时间: 2024-10-12 17:22:20