iOS开发之多线程

作者: Ego_1973 | 来源:发表于2016-11-18 16:42 被阅读0次

    一.NSThread

    查看当前线程: [NSThread currentThread];

    // 1. 子线程的创建
    //  (1.)
    NSURL *url = [NSURL URLWithString:@""];
    [NSThread detachNewThreadSelector:@selector(downloadImage:) toTarget:self withObject:url];
    //  (2.)更灵活
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(downloadImage:) object:url];
    [thread start];
    
    // 2. 在子线程中召唤主线程做事

    // 如果waitUntilDone参数为yes,那么当前线程会被阻挡,直到selector运行完

    [self performSelectorOnMainThread:@selector(buttonAction) withObject:nil waitUntilDone:YES];
    

    二.GCD

    1.并发队列:
    全局队列:dispatch_get_global_queue,自己创建
    2.串行队列:
    主队列:dispatch_get_main_queue 自己创建

    ---任务:block
    ---函数:sync(同步),async(异步)
    ---单例模式

    1. 重写allocWithZone(由于alloc会调用allocWithZone)
    2. 重写copyWithZone(调用allocWithZone方法即可)
    3. 提供shaer开头的类方法。

    ---NSOperation
    ---RunLoop

    1.同一时间只能选择一个模式运行
    2.自己开辟的子线程需要手动启用runloop
    3.模式下有source(事件源), NSTimer(定时器),observe(观察者)
    4.自己开辟的子线程必须添加事件源,或者定时器,启动runloop才不会停止。
    常用模式
    Default:默认
    Tracking:拖拽UIScrollView

    // 数据解析

    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    }];
    [task resume];
    

    // 回到主线程
    // <1>

     [self performSelectorOnMainThread:@selector(downloadImage:) withObject:self waitUntilDone:YES];
    

    // <2>

    [self performSelector:@selector(downloadImage:) onThread:[NSThread mainThread] withObject:self waitUntilDone:YES];
    

    // <3> 异步+主队列
    // 从子线程回到主线程,(子线程下载,耗时操作),主线程刷新UI

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
       //  执行耗时的异步操作
        dispatch_async(dispatch_get_main_queue(), ^{
           //  回到主线程,执行UI刷新操作
        });
    });
    

    // 1.同步函数+串行队列/并发队列 按顺序执行
    // 2.异步函数+串行队列 开启一条子线程,按顺序执行
    // 3.异步函数+并发队列 开启多条线程,无序同时进行

    //  想在开启的子线程中监听事件,需要开启子线程循环
    //  开启子线程
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSTimer *timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(imageDownloader) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];
        CFRunLoopRun();// 开启一个子线程循环
        // 强制退出线程
        [NSThread exit];
        NSLog(@"线程执行结束");
    });
    

    // Once Time Code

    - (void)oneTest {
    [self performSelectorInBackground:@selector(onceTimeAction) withObject:nil];
    [NSThread detachNewThreadSelector:@selector(onceTimeAction) toTarget:self withObject:nil];
    [self onceTimeAction];
    }
    
    
    - (void)onceTimeAction {
    // GCD中的一次性代码,能够保证线程安全
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSLog(@"一次性代码,只执行一次");
    });
    

    }

    // GCD之网络请求
    // 首先创建并行队列,创建队列组,将队列和需要处理的网络请求分别添加到组中,当组中所有队列处理完事件后调用dispatch_group_notify,我们需要在里边处理事件。由于队列在处理网络请求时将”发送完一个请求”作为事件完成的标记(此时还未获得网络请求返回数据),所以在这里需要用信号量进行控制,在执行dispatch_group_notify前发起信号等待(三次信号等待,分别对应每个队列的信号通知),在每个队列获取到网络请求返回数据时发出信号通知。这样就能完成需求中的要求。

    // 如果需求中改为:同时存在A,B,C三个任务,要求ABC依次进行处理,当上一个完成时再进行下一个任务,当三个任务都完成时再处理事件。这时只需要将队列改为串行队列即可(不需要信号量控制)。

    // 创建信号量
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    // 创建全局并行
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, queue, ^{
       
             [self oneRequest];
        
        dispatch_semaphore_signal(semaphore);
    });
    dispatch_group_async(group, queue, ^{
        
               [self twoRequest];
        
        dispatch_semaphore_signal(semaphore);
    });
    dispatch_group_async(group, queue, ^{
        
            [self threeRequest];
        
        dispatch_semaphore_signal(semaphore);
    });
    
    dispatch_group_notify(group, queue, ^{
        // 三个请求对应三次信号等待
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    });

    相关文章

      网友评论

        本文标题:iOS开发之多线程

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