GCD几种简单用法

//1.同步  顺序执行

- (void)test1

{

    dispatch_async(mainQueue, ^{

        [self doSomeThing:@"A"];

    });

    dispatch_async(mainQueue, ^{

       [self doSomeThing:@"B"];

    });

    dispatch_async(mainQueue, ^{

        [self doSomeThing:@"C"];

    });

}


//2.异步同时进行

- (void)test2

{

    dispatch_async(globalQueue, ^{

        [self doSomeThing:@"A"];

    });

    dispatch_async(globalQueue, ^{

        [self doSomeThing:@"B"];

    });

    dispatch_async(globalQueue, ^{

        [self doSomeThing:@"C"];

    });

}


//3.A B同时进行  最后执行C

- (void)test3

{

    dispatch_group_t group = dispatch_group_create();

    

    dispatch_group_async(group, globalQueue, ^{

        [self doSomeThing:@"A"];

    });

    dispatch_group_async(group, globalQueue, ^{

        [self doSomeThing:@"B"];

    });

    dispatch_group_async(group, globalQueue, ^{

        [self doSomeThing:@"C"];

    });

    dispatch_group_async(group, globalQueue, ^{

        [self doSomeThing:@"D"];

    });

    

    dispatch_group_notify(group, globalQueue, ^{

        [self doSomeThing:[NSString stringWithFormat@"最后执行----%d",[NSThread isMainThread]]];

        dispatch_async(mainQueue, ^{

            [self doSomeThing:[NSString stringWithFormat@"主线程刷新UI----%d",[NSThread isMainThread]]];

        });

    });

}


//4.自定义队列   自定义执行顺序  可串行  可并行

- (void)test4

{

   

    dispatch_queue_t customQueue = dispatch_queue_create("anfu", DISPATCH_QUEUE_CONCURRENT);

    

    dispatch_async(customQueue, ^{

        [self doSomeThing:@"A"];

    });

    dispatch_async(customQueue, ^{

       [self doSomeThing:@"B"];

    });

    

    dispatch_barrier_async(customQueue, ^{

        [self doSomeThing:@"C"];

    });

    

    dispatch_async(customQueue, ^{

        [self doSomeThing:@"D"];

    });

    dispatch_async(customQueue, ^{

        [self doSomeThing:@"E"];

    });

    

}


//5.延迟调用

- (void)test5

{

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 *NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        [self doSomeThing:@"1秒后执行"];

    });

}


//6.调用多次

- (void)test6

{

    dispatch_apply(10globalQueue, ^(size_t time) {

        NSLog(@"%zu",time);

    });

}


//7.只调用一次,一般在单例中使用

- (void)test7

{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        NSLog(@"只调用一次");

    }); 

}

//公共调用方法

- (void)doSomeThing:(NSString *)obj

{

    sleep(1);

    NSLog(@"%@",obj);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值