[OC] 线程 dispatch_group_t

- (void)groupEvent{
    //创建线程
    dispatch_group_t group =dispatch_group_create();
    dispatch_queue_t globalQueue=dispatch_get_global_queue(0, 0);
 
    dispatch_group_enter(group);
    
    //模拟多线程耗时操作
    dispatch_group_async(group, globalQueue, ^{
        sleep(3);
        NSLog(@"%@---block1结束。。。",[NSThread currentThread]);
        dispatch_group_leave(group);
    });

    NSLog(@"%@---1NSLOG结束。。。",[NSThread currentThread]);
    
    dispatch_group_enter(group);
    //模拟多线程耗时操作
    dispatch_group_async(group, globalQueue, ^{
        sleep(3);
        NSLog(@"%@---block2结束。。。",[NSThread currentThread]);
        dispatch_group_leave(group);
    });

    NSLog(@"%@---2NSLOG结束。。。",[NSThread currentThread]);
//线程全部结束 dispatch_group_notify(group, dispatch_get_global_queue(
0, 0), ^{ NSLog(@"%@---全部结束。。。",[NSThread currentThread]); }); }

上面的代码的后台输出是:

2016-12-23 09:46:27.853 CPMNetworking[1341:36092] <NSThread: 0x600000068600>{number = 1, name = main}---1NSLOG结束。。。
2016-12-23 09:46:27.856 CPMNetworking[1341:36092] <NSThread: 0x600000068600>{number = 1, name = main}---2NSLOG结束。。。
2016-12-23 09:46:30.923 CPMNetworking[1341:36550] <NSThread: 0x608000263f00>{number = 4, name = (null)}---block1结束。。。
2016-12-23 09:46:30.930 CPMNetworking[1341:36176] <NSThread: 0x6000002647c0>{number = 5, name = (null)}---block2结束。。。
2016-12-23 09:46:30.930 CPMNetworking[1341:36176] <NSThread: 0x6000002647c0>{number = 5, name = (null)}---全部结束。。。

可以发现,因为block内被加了休眠sleep,所以block外的NSLOG操作被先执行了。而在block1被执行完毕后,block2和线程结束的部分的内容才被执行

posted @ 2018-11-07 09:06  Oran  阅读(369)  评论(0编辑  收藏  举报