@SanMao
2015-12-08T12:41:03.000000Z
字数 2254
阅读 1250
多线程
#pragma mark - 延迟执行- (void)delay{dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{NSLog(@"延时执行");NSLog(@"%@",[NSThread currentThread]);});}
#pragma mark - 只执行一次- (void)once{// 只执行1次的代码(这里面默认是线程安全的)static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{NSLog(@"%@",[NSThread currentThread]);NSLog(@"执行了");});}
#pragma mark - 快速迭代- (void)apply{// 获取来源文件夹路径和目的文件夹路径NSString *source = @"/Users/V/Desktop/source";NSString *destilation = @"/Users/V/Desktop/destilation";// 获取文件管理者NSFileManager *mgr = [NSFileManager defaultManager];// 获取来源文件夹中所有文件的名称NSArray *names = [mgr subpathsAtPath:source];// NSLog(@"%@",names);// 记录开始时间CFAbsoluteTime begin = CFAbsoluteTimeGetCurrent();// 快速迭代dispatch_apply(names.count, dispatch_get_global_queue(0, 0), ^(size_t index) {// 获取当前遍历到得文件的名称NSString *fileName = names[index];// 拼接源文件的文件的全路径NSString *souPath = [source stringByAppendingPathComponent:fileName];// 拼接目标文件夹的文件全路径NSString *desPath = [destilation stringByAppendingPathComponent:fileName];// 从源文件夹剪切文件到目标文件夹[mgr moveItemAtPath:souPath toPath:desPath error:nil];});// 记录结束的时间CFAbsoluteTime end = CFAbsoluteTimeGetCurrent();NSLog(@"总共耗时:%f",end - begin);}
这个queue不能是全局的并发队列
#pragma mark - 栅栏,栅栏之前的执行完了才能执行栅栏,栅栏执行完了才能执行栅栏之后的代码- (void)barrier{// 创建队列dispatch_queue_t queue = dispatch_queue_create("fsgergr", DISPATCH_QUEUE_CONCURRENT);// 添加任务dispatch_async(queue, ^{NSLog(@"1 -- %@",[NSThread currentThread]);});dispatch_async(queue, ^{NSLog(@"2 -- %@",[NSThread currentThread]);});dispatch_async(queue, ^{NSLog(@"3 -- %@",[NSThread currentThread]);});dispatch_barrier_async(queue, ^{NSLog(@"barrier -- %@",[NSThread currentThread]);});dispatch_async(queue, ^{NSLog(@"4 -- %@",[NSThread currentThread]);});dispatch_async(queue, ^{NSLog(@"5 -- %@",[NSThread currentThread]);});}
dispatch_group_t group = dispatch_group_create();dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{// 执行1个耗时的异步操作});dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{// 执行1个耗时的异步操作});dispatch_group_notify(group, dispatch_get_main_queue(), ^{// 等前面的异步操作都执行完毕后,回到主线程...});