博客> IOS 线程的一些理解与使用
IOS 线程的一些理解与使用
2017-11-23 00:25 评论:0 阅读:270 liudhkk
ios GCD 多线程 并发队列

好处 1)使用线程可以把程序中占据时间长的任务放到后台去处理,如图片、视频下载 2)发挥多核处理器的优势,并发执行让系统运行的更快、更流畅,用户体验更好 缺点 1)大量的程序降低代码的可读性 2)更多的线程需要更多的空间 3)当多个线程对同一个资源出现争夺的时候需要注意线程安全问题 线程使用: 1)NSThread(两种创建方式)

[NSThread detachNewThreadSelector:@selector(threadBegin:) toTarget:self withObject:@1];

NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(threadBegin:) object:@1];

[thread1 start];

2)NSOperationQueue

__weak typeof(self) weakSelf = self;

    [[NSOperationQueue new] addOperationWithBlock:^{

        [weakSelf threadBegin:@1];

    }];

    NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{

        [weakSelf threadBegin:@2];

    }];

    [op addExecutionBlock:^{

        [weakSelf threadBegin:@3];

    }];

    [op addExecutionBlock:^{

        [NSThread sleepForTimeInterval:1];

        [weakSelf threadBegin:@4];

    }];

    [op addExecutionBlock:^{

        [weakSelf threadBegin:@6];

    }];

    [op start];

3)GCD

dispatch_async(dispatch_get_global_queue(0, 0), ^{ //异步

 [weakSelf threadBegin:@1];

 });

 dispatch_group_t group = dispatch_group_create(); // 异步组合

 dispatch_queue_t queue = dispatch_get_global_queue(0, 0);

 dispatch_group_async(group, queue, ^{

 [weakSelf threadBegin:@2];

 });

 dispatch_group_async(group, queue, ^{

 [weakSelf threadBegin:@3];

 });

 dispatch_group_notify(group, queue, ^{

 [weakSelf threadBegin:@4];

 });

 // 异步延时

 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{

 [weakSelf threadBegin:@5];

 });
收藏
0
sina weixin mail 回到顶部