1. 一个接口的恳求,依赖于另一个恳求的成果
  • 运用GCD组队列中的dispatch_group_asyncdispatch_group_notify
- (void)dispatchGroup{
    dispatch_queue_t queue = dispatch_queue_create("com.test", DISPATCH_QUEUE_CONCURRENT);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, queue, ^{
        // 恳求1
        NSLog(@"11111");
    });
    dispatch_group_notify(group, queue, ^{
        // 恳求2
        NSLog(@"2222222");
    });
}
  • 运用GCD的栅栏函数dispatch_barrier_async
- (void)dispatchBarrier{
    dispatch_queue_t queue = dispatch_queue_create("com.test", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        // 恳求1
        NSLog(@"11111");
    });
    dispatch_barrier_async(queue, ^{
        // 恳求2
        NSLog(@"22222");
    });
}
  • 运用GCD的信号量dispatch_semaphore,信号量的初始值可以用来操控线程并发访问的最大数量。假如设置为1则为串行履行,到达线程同步的意图
- (void)dispatchSemaphore{
    dispatch_queue_t queue = dispatch_queue_create("com.test", DISPATCH_QUEUE_CONCURRENT);
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    dispatch_async(queue, ^{
        NSLog(@"11111");
        // 恳求1完毕后 增加信号个数,dispatch_semaphore_signal()信号加1
        dispatch_semaphore_signal(semaphore);
    });
    dispatch_async(queue, ^{
        // 无限等候,直到恳求1完毕 增加了信号量,大于0后才开端,dispatch_semaphore_wait()信号减1
        // 假如信号量的值 > 0,就让信号量的值减1,然后持续往下履行代码
        // 假如信号量的值 <= 0,就会休眠等候,直到信号量的值变成>0,就让信号量的值减1,然后持续往下履行代码
        // DISPATCH_TIME_FOREVER 这个是一向等候的意思
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        // 恳求2开端
        NSLog(@"22222");
    });
}
  1. 在异步线程中return一个字符串
  • 模拟异步线程办法,需要return字符串@"小熊"
- (void)asyncRequestMethod:(void(^)(NSString *name))successBlock{
    dispatch_queue_t queue = dispatch_queue_create("com.test", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{
        if (successBlock) {
            successBlock(@"小熊");
        }
    });
}
  • while循环等候堵塞线程办法
- (NSString *)nameStr{
    __block NSString *nameStr = @"小关";
    __block BOOL isSleep = YES;
    [self asyncRequestMethod:^(NSString *name) {
        nameStr = name;
        NSLog(@"1");
        isSleep = NO;
        NSLog(@"3");
    }];
    //while循环等候堵塞线程
    while (isSleep) {
        NSLog(@"4");
    }
    NSLog(@"2");
    return nameStr;
}
  • 用信号量操控,异步改同步
- (NSString *)nameStr{
    __block NSString *nameStr = @"小关";
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    [self asyncRequestMethod:^(NSString *name) {
        nameStr = name;
        dispatch_semaphore_signal(semaphore);
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    return nameStr;
}
  • 利用dispatch_group_t调度组,异步改同步
- (NSString *)nameStr{
    __block NSString *nameStr = @"小关";
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    [self asyncRequestMethod:^(NSString *name) {
        nameStr = name;
        dispatch_group_leave(group);
    }];
    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
    return nameStr;
}

附:GrandCentralDispatchDemo