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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值