GCD问题-三个异步任务执行完毕后再执行另外一个任务

划重点:注意是三个异步任务,直接用dispatch_group是行不通的。
暂时想到了三种方法:

1、利用dispatch_group_enter、leave特性。

这两个方法类似信号量dispatch_group_enter +1 、dispatch_group_leave -1。当为0时调用dispatch_group_notify方法,并且dispatch_group_wait停止等待。

代码如下:
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    dispatch_async(queue, ^{
        sleep(2);
        NSLog(@"任务1执行");
        dispatch_group_leave(group);
    });
    dispatch_group_enter(group);
    dispatch_async(queue, ^{
        sleep(3);
        NSLog(@"任务2执行");
        dispatch_group_leave(group);
    });
    dispatch_group_enter(group);
    dispatch_async(queue, ^{
        sleep(4);
        NSLog(@"任务3执行");
        dispatch_group_leave(group);
    });
    dispatch_group_notify(group, queue, ^{
        NSLog(@"notify执行");
    });

2、用信号量

信号量大于0资源可用、否则会进行等待、原理跟方法1差不多

    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_group_t group = dispatch_group_create();
    dispatch_semaphore_t semphore = dispatch_semaphore_create(0);
    dispatch_async(queue, ^{
        sleep(2);
        NSLog(@"任务1执行");
        dispatch_semaphore_signal(semphore);
    });
    dispatch_async(queue, ^{
        sleep(3);
        NSLog(@"任务2执行");
        dispatch_semaphore_signal(semphore);
    });
    dispatch_async(queue, ^{
        sleep(4);
        NSLog(@"任务3执行");
        dispatch_semaphore_signal(semphore);
    });
    dispatch_semaphore_wait(semphore, DISPATCH_TIME_FOREVER);
    dispatch_semaphore_wait(semphore, DISPATCH_TIME_FOREVER);
    dispatch_semaphore_wait(semphore, DISPATCH_TIME_FOREVER);
    NSLog(@"执行等待");

你问我为啥写了3个dispatch_semaphore_wait~~~,因为信号量初始化不能为负值啊。。。。这点欢迎大神指点。

3、kvo

创建一个属性kvo观察其值当值降为0时,执行该任务

    self.num = @"";
    [self addObserver:self forKeyPath:@"num" options:NSKeyValueObservingOptionNew context:nil];
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
        sleep(2);
        NSLog(@"任务1执行");
       self.num = [self.num stringByAppendingString:@"+"];
    });
    dispatch_async(queue, ^{
        sleep(3);
        NSLog(@"任务2执行");
        self.num = [self.num stringByAppendingString:@"+"];
    });
    dispatch_async(queue, ^{
        sleep(4);
        NSLog(@"任务3执行");
       self.num = [self.num stringByAppendingString:@"+"];
    });

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([self.num isEqualToString:@"+++"]){
         NSLog(@"执行任务");
    }
}

其他方法欢迎留言哦!

你可能感兴趣的:(GCD问题-三个异步任务执行完毕后再执行另外一个任务)