美文网首页
iOS 学习GCD(持续更新)

iOS 学习GCD(持续更新)

作者: 我唔知啊 | 来源:发表于2017-03-03 22:42 被阅读6次

    目的:执行完第一个任务再执行第二个任务

    方法一:dispatch_barrier_async配合DISPATCH_QUEUE_CONCURRENT线程,先执行barrier前面的任务,再执行后面的任务。
    - (void)barrier {
        // 必须用DISPATCH_QUEUE_CONCURRENT,dispatch_barrier_async才有作用
        dispatch_queue_t queue = dispatch_queue_create("concurrent", DISPATCH_QUEUE_CONCURRENT);
        dispatch_async(queue, ^{
            NSLog(@"1-----%@",[NSThread currentThread]);
        });
        dispatch_async(queue, ^{
            NSLog(@"2-----%@",[NSThread currentThread]);
        });
        // 执行完barrier之前的任务才能执行barrier之后的任务
        dispatch_barrier_async(queue, ^{
            NSLog(@"barrier------%@",[NSThread currentThread]);
        });
        dispatch_async(queue, ^{
            NSLog(@"3-----%@",[NSThread currentThread]);
        });
        dispatch_async(queue, ^{
            NSLog(@"4-----%@",[NSThread currentThread]);
        });
    }
    
    方法二:dispatch_group_enter和dispatch_group_leave
    - (void)enterThenLeave {
        // 创建线程组
        dispatch_group_t group = dispatch_group_create();
        dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // 1、2并行
            dispatch_group_enter(group);// 添加任务开始标识
            for (NSInteger i = 0; i < 2; i ++) {
                NSLog(@"2-----%@",[NSThread currentThread]);
                if (i == 1) {
                    dispatch_group_leave(group);// 添加任务结束标识
                }
            }
           
            dispatch_group_enter(group);
            for (NSInteger i = 0; i < 2; i ++) {
                NSLog(@"1-----%@",[NSThread currentThread]);
                if (i == 1) {
                    dispatch_group_leave(group);
                }
            }
        });
        // 所有任务都执行dispatch_group_leave后才执行这个方法
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            NSLog(@"3------");
        });
    }
    

    相关文章

      网友评论

          本文标题:iOS 学习GCD(持续更新)

          本文链接:https://www.haomeiwen.com/subject/sezrgttx.html