iOS开发中在指定的某些线程执行完之后去执行其他线程

背景:

有四个线程A、B、C、D。

需求:

在A、B线程执行完之后去执行线程C、D。

实现方式:

GCD

1.利用GCD中的barrier

2.利用GCD中的group

    2.1 利用在组中所有的线程执行完之后再去执行其他的线程

    2.2 利用wait


代码:

barrier:


group相关代码:

// 全局变量group

    dispatch_group_t group = dispatch_group_create();

    // 并行队列

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    // 进入组(进入组和离开组必须成对出现, 否则会造成死锁)

    dispatch_group_enter(group);

    dispatch_group_async(group, queue, ^{

        // 执行异步任务1

        [NSThread sleepForTimeInterval:2];

        for (int i = 0; i < 3; i ++) {

            NSLog(@"1---%@",[NSThread currentThread ]);    // 子线程

        }

        _str1 = @"str1";

        dispatch_group_leave(group);

    });


    // 进入组

    dispatch_group_enter(group);

    dispatch_group_async(group, queue, ^{

        // 执行异步任务2

        [NSThread sleepForTimeInterval:2];

        for (int i = 3; i < 6; i ++) {

            NSLog(@"2---%@",[NSThread currentThread ]);

        }

        _str2 = @"str2";

        dispatch_group_leave(group);


    });

    // wait

    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);


    dispatch_async(dispatch_get_global_queue(0, 0), ^{

        NSLog(@"%@", [NSThread currentThread]);

        _str1 = @"str..";

        dispatch_async(dispatch_get_main_queue(), ^{

            NSLog(@"%@", _str1);

            NSLog(@"%@", _str2);

            NSLog(@"%@", [NSThread currentThread]); // 主线程

        });

    });


    return;

    dispatch_group_notify(group, queue, ^{  // 监听组里所有线程完成的情况


        dispatch_async(dispatch_get_global_queue(0, 0), ^{

          NSLog(@"%@", [NSThread currentThread]);

            _str1 = @"str..";


            dispatch_async(dispatch_get_main_queue(), ^{

                NSLog(@"%@", _str1);

                NSLog(@"%@", _str2);

                NSLog(@"%@", [NSThread currentThread]); // 主线程

                NSLog(@"完成...");

            });


        });


    });

demo地址:https://gitee.com/liangsenliangsen/dispatch_group

本篇文章到这里就结束了,愿大家加班不多工资多,男同胞都有女朋友,女同胞都有男朋友。😊

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • NSThread 第一种:通过NSThread的对象方法 NSThread *thread = [[NSThrea...
    攻城狮GG阅读 859评论 0 3
  • 通过这篇文章,再熟悉一下多线程,这里主要是根据自己的理解,来介绍一下多线程 iOS有三种多线程编程的技术,分别是:...
    pengmengli阅读 293评论 0 0
  • #import "ViewController.h" @interface ViewController () @...
    艾克12138阅读 226评论 0 0
  • 再也不会有 明年继续 吃到了期待已久的棉花糖巧克力 一直很想喝的热巧克力,上面要撒上棉花糖,没想到学校party上...
    花木雀跃是紫紫阅读 86评论 0 0
  • 人生最幸运的事,莫过于有一两知己。而这一两知己还是充满正能量的。而我的生命中,最有正能的知己,莫过于我的好闺蜜...
    小汐0314阅读 222评论 2 2