iOS多线程

NSThread,NSOperation,GCD 抽象层次是从低到高的,抽象度越高的使用越简单。

NSThread

优点:在所有的多线程实现方式中 最轻量级。比其它两个更轻。
可以按照需求 任意控制thread对象 即:线程的加锁等操作
缺点:需要自己维护线程的生命周期和线程的同步和互斥,但是这些都需要耗费系统的资源。控制太繁琐 不能自己控制线程安全
//NSThread 的一个对象 就代表一个线程

      //创建 NSThread对象
      [NSThread detachNewThreadSelector:@selector(threadStart:) toTarget:self withObject:nil];

    thread = [[NSThread alloc]initWithTarget:self selector:@selector(threadStart:) object:nil];
    // 指定名称
    thread.name = @"yy";
    //开启NSThread
    [thread start];
    //取消thread运行
    [thread cancel];
    // 判断当前任务是否为主线程  0为不是 1为是
    BOOL b = [NSThread isMainThread];

NSOperation

NSOperation代表一个任务 自己不能实现多线程。NSOperationQueue可以实现多线程
NSOperation是一个抽象类 不能直接使用, 需要创建一个子类去编写实现的内容,子类NSBlockOperation、NSInvocationOperation
不需要自己管理线程的生命周期和线程的同步和互斥等。只是需要关注自己的业务逻辑处理,需要和NSOperationQueue一起使用

    NSOperation * op = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(operationRun:) object:nil];
    [op start];
    // 任务队列(NSOperationQueue) 内部管理一系列的线程
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    //最大并发线程数量
    queue.maxConcurrentOperationCount = 3;
    for (int i = 0 ; i< 5; i++) {
           NSInvocationOperation * op = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(operationRun:) object:nil];
        op.name = [NSString stringWithFormat:@"InvocationOperation%d",i];
        [queue addOperation:op];
    }

GCD 是基于队列的 多线程实现方式

 比前面两者更高效更强大,更方便。
 参考

GCD理解(一)
GCD理解(二)
GCD理解(三)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值