网络请求或者操作并发执行,顺序执行,线程结束依次执行

一、并发执行

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, queue, ^{
        //操作一
        NSLog(@"任务一完成");
    });
    
    dispatch_group_async(group, queue, ^{
        //操作二
        NSLog(@"任务二完成");
    });
    
    dispatch_group_async(group, queue, ^{
        //操作三
        NSLog(@"任务三完成");
    });
    //在分组的所有任务完成后触发
    dispatch_group_notify(group, queue, ^{
        NSLog(@"所有任务完成");
    });

如果操作是异步的,结果可能是

 任务二完成
 任务三完成
 任务一完成
所有任务完成

二、顺序执行

// 利用线程依赖关系测试
    __weak typeof (self)weakSelf =self;
    
    NSBlockOperation * operation1 = [NSBlockOperation blockOperationWithBlock:^{
        [weakSelf operationA];
        NSLog(@"任务一完成");
    }];
    NSBlockOperation * operation2 = [NSBlockOperation blockOperationWithBlock:^{
        [weakSelf  operationB];
        NSLog(@"任务二完成");
    }];
    NSBlockOperation * operation3 = [NSBlockOperation blockOperationWithBlock:^{
        [weakSelf  operationC];
        NSLog(@"任务三完成");
    }];
    [operation2 addDependency:operation1]; //operation2的执行依赖于operation1的完成
    [operation3 addDependency:operation2];
    NSOperationQueue * queue = [[NSOperationQueue alloc]init];
    [queue addOperations:@[operation1,operation2,operation3] waitUntilFinished:NO];

operation的网络请求操作

-(void) operation A{
    
    //创建信号量并设置计数默认为0
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];;
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",nil];
    [manager GET:@"http://qr.bookln.cn/qr.html?crcode=110000000F00000000000000B3ZX1CEC" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        dispatch_semaphore_signal(sema);
        NSLog(@"正在执行A");
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        ////计数+1操作
        
        dispatch_semaphore_signal(sema);
        NSLog(@"执行错误A");
        
    }];
    
    NSLog(@"正在刷新A");
    //若计数为0则一直等待
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    NSLog(@"已经刷新A");
}

结果可能是

 任务一完成
 任务二完成
 任务三完成 

你可能感兴趣的:(网络请求或者操作并发执行,顺序执行,线程结束依次执行)