iOS -GCD

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

//     处理数据,网络请求,

        

        dispatch_async(dispatch_get_main_queue(), ^{

//     在此处刷新UI界面

        });

    });

   

    

    

//    利用GCD延迟执行任务的方法

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

        NSLog(@"1");

    double delayInSeconds=2.0;

    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds*NSEC_PER_SEC);

    dispatch_after(popTime,dispatch_get_main_queue(), ^(void){

        // code to be executed on the main queue after delay

        NSLog(@"2");


    });

 });

   

    

//    利用GCD组运行分为并行和串行

//    并行

    dispatch_queue_t queue;

    queue=dispatch_queue_create("MyQueue",NULL);

    dispatch_async(queue, ^{

        printf("Do\n");

    });

    dispatch_async(queue, ^{

        printf("some\n");

    });

    dispatch_async(queue, ^{

        printf("work here.\n");

    });

//  这个先执行 然后再执行上边的输出

    printf("The first block may or may not have run.\n");


    

//  串行

//    先执行Do some more here  然后再执行BOth blocks have completed

    dispatch_sync(queue, ^{

        printf("Do some more work here.\n");

    });

    printf("Both blocks have completed.\n");

    

    

//    并行与串行混编

//    执行task1 task2 task3 都运行完成以后才异步运行 task4 task5 task6 我们该怎么做呢?这里我们可以引入group的概念

    dispatch_queue_t aDQueue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);

    dispatch_group_t group =dispatch_group_create();

//    Add a task to the group

    dispatch_group_async(group, aDQueue, ^{

        printf("task 1 \n");

    });

    dispatch_group_async(group, aDQueue, ^{

        printf("task 2 \n");

    });

    dispatch_group_async(group, aDQueue, ^{

        printf("task 3 \n");

    });

    printf("wait 1 2 3\n");

    

    dispatch_group_wait(group,DISPATCH_TIME_FOREVER);

    printf("task 1 2 3 finished\n");

    

    group=dispatch_group_create();

//    add a task to the group

    dispatch_group_async(group, aDQueue, ^{

        printf("task 4 \n");


    });

    dispatch_group_async(group, aDQueue, ^{

        printf("task 5 \n");

    });

    dispatch_group_async(group, aDQueue, ^{

        printf("task 6 \n");

    });

    printf("wait 4 5 6 \n");

    dispatch_group_wait(group,DISPATCH_TIME_FOREVER);

    printf("task 4 5 6 finished \n");


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值