zoukankan      html  css  js  c++  java
  • ios中多线程GCD NSOperation NSThread 相关的操作解析

        //1、GCD 继承自C语言 优点 简单方便

        //开启一个子线程处理耗时的操作

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

            

        //在主线程处理UI更新相关的操作

        dispatch_async(dispatch_get_main_queue(), ^{

            

            

        });

        });

        

        //延时操作

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            

            

        });

        //确保程序只会运行一次,类似于锁

        static dispatch_once_t onceToken;

        dispatch_once(&onceToken, ^{

            

        });

        //确保程序只会运行一次

        @synchronized (self) {

            

        }

            

        // 2、NSOperation NSOperationQueue  是对GCD更高一层的封装 可以添加依赖和设置优先级更好的控制和管理线程的并发操作 缺点:操作比GCD稍慢

        NSBlockOperation *block=[NSBlockOperation blockOperationWithBlock:^{

            

        }];

        

        NSInvocationOperation *invo=[[NSInvocationOperation alloc]initWithTarget:self selector:@selector(btnOperate) object:nil];

        

        NSOperationQueue *queue=[[NSOperationQueue alloc]init];

        //添加依赖,设置操作

        [block addDependency:invo];

        //设置操作优先级

        block.queuePriority=NSOperationQueuePriorityLow;

        invo.queuePriority=NSOperationQueuePriorityHigh;

        [queue addOperation:block];

        [queue addOperation:invo];

        

        //3、NSThread 是一种轻量级的 需要管理线程的生命周期和并发操作

        NSThread *thread=[[NSThread alloc]initWithTarget:self selector:@selector(addBtnTypeCss:) object:nil];

        //线程的开启

        [thread start];

        //线程的取消

        [thread cancel];

        //等到某个日期

        [NSThread sleepUntilDate:[NSDate date]];

        //设置等待多久唤起

        [NSThread sleepForTimeInterval:1];

  • 相关阅读:
    错误:CS0234: 命名空间“System”中不存在类型或命名空间名称“Linq”的解决方法
    DotNetNuke中Membership Provider机制
    解决异常“SqlParameterCollection 只接受非空的 SqlParameter 类型对象。”
    使用 Membership.ValidateUser(Login1.UserName, Login1.Password)验证用户
    布隆过滤器应用
    Paxos在大型系统中常见的应用场景(转)
    淘宝MapReduce作业特性分析(转)
    淘宝Hadoop集群的概况(转)
    内核模块管理(转)
    Centos启动流程(转)
  • 原文地址:https://www.cnblogs.com/bigant9527/p/14046801.html
Copyright © 2011-2022 走看看