多线程

作者: Alan龙马 | 来源:发表于2019-03-04 13:51 被阅读0次

    线程
    多线程GCD
    https://www.jianshu.com/p/667ec9e612ad

    #----打印当前线程
        NSLog(@"currentThread:%@",[NSThread currentThread]);
    
    #----判断是否主线程
     if (strcmp(dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL), dispatch_queue_get_label(dispatch_get_main_queue())) == 0) {
                // do something in main thread
                NSLog(@"--main thread");
            } else {
                // do something in other thread
                NSLog(@"--other thread");
                
            }
    
    
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
           //费时操作
            NSInteger size = [[SDImageCache sharedImageCache] getSize];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSString *sizeStr = [self fileSizeWithInterge:size];
                
            });
            
        });
    

    线程组

    日志分析:
    1:系统会为每个异步任务开辟一条子线程;
    2:每个任务在开辟的子线程中执行;
    3:在dispatch_group_notify监听到回调之后,此时还在某条子线程中;需要编写回到主线程的语句
    4:不会造成主线程堵塞;
    强狂三:解决场景:执行完多个异步任务之后才执行某一任务 (举例:在异步任务中发起多个获取网络图片的异步请求,等到图片都获取成功之后再进行UI界面的刷新)
    解决办法:
    
    
    dispatch_queue_t queueT = dispatch_queue_create("group.queue", DISPATCH_QUEUE_CONCURRENT);//一个并发队列
    dispatch_group_t grpupT = dispatch_group_create();//一个线程组
    
    dispatch_group_async(grpupT, queueT, ^{
        NSLog(@"group——当前线程一");
        //模仿网络请求代码
        dispatch_group_enter(grpupT);
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            for (int i = 0; i < 10; i++) {
                [NSThread sleepForTimeInterval:1];
                NSLog(@"网络图片请求中 ···%d", i);
            }
            dispatch_group_leave(grpupT);
        });
        
    });
    
    dispatch_group_async(grpupT, queueT, ^{
        NSLog(@"group——当前线程二");
        //模仿网络请求代码
        dispatch_group_enter(grpupT);
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            for (int i = 0; i < 10; i++) {
                [NSThread sleepForTimeInterval:1];
                NSLog(@"网络图片2请求中 ···2_%d", i);
            }
            dispatch_group_leave(grpupT);
        });
        
    });
    
    dispatch_group_async(grpupT, queueT, ^{
        NSLog(@"group——当前线程三");
        //模仿网络请求代码
        dispatch_group_enter(grpupT);
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            for (int i = 0; i < 10; i++) {
                [NSThread sleepForTimeInterval:1];
                NSLog(@"网络图片3请求中 ···3_%d", i);
            }
             dispatch_group_leave(grpupT);
        });
       
    });
    
    
    
    dispatch_group_notify(grpupT, queueT, ^{
        
        NSLog(@"此时还是在子线程中");
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"回到主线程");
        });
        
    });
    

    相关文章

      网友评论

          本文标题:多线程

          本文链接:https://www.haomeiwen.com/subject/ntxiuqtx.html