zoukankan      html  css  js  c++  java
  • NSThread基础使用

    1.创建和启动线程
     
    一个NSThread对象就代表一条线程;
     
    创建,启动线程
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    [thread start];
    2.线程相关用法
     
    主线程相关用法
    1 + (NSThread *)mainThread;
    2 - (BOOL)isMainThread;
    3 + (BOOL)isMainThread;
    获得当前线程
    1 NSThread *current = [NSThread currentThread];
     
    线程的调度优先级
    1 + (double)threadPriority;
    2 + (BOOL)setThreadPriority:(double)p;
    3 - (double)threadPriority;
    4 - (BOOL)setThreadPriority:(double)p;
    调度的优先级取值范围是0.0 ~ 1.0, 默认0.5, 值越大, 优先级越高;
     
    线程的名字
    1 - (void) setName:(NSString *)n;
    2 - (NSString *)name;
    创建线程后自动启动线程
    1 [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
     
    隐式创建线程并启动线程
    1 [self performSelectorInBackground:@selector(run) withObject:nil];
     
    3.线程的五种状态
    新建(New) 就绪(Runnable) 运行(Running) 阻塞(Blocked) 死亡(Dead)
     
    4.控制线程状态
    启动线程
    1 - (void)start;
     
    阻塞线程
    1 + (void)sleepUntilDate:(NSDate *)date;
    2 + (void)sleepForTimeInterval:(NSTimeInterval)ti;
     
    强制停止线程
    1 + (void)exit;
     
    5.多线程的安全隐患
    资源共享:多个线程访问同一块资源;
    处理共享数据时很容易引发数据错乱和数据安全问题;
     
    6.安全隐患解决--互斥锁
     
    互斥锁使用格式:@synchroniazed(锁对象) { 代码 }
     
    互斥锁的优缺点:
    优点:能有效防止因多线程抢夺资源造成的数据安全问题;
    缺点:大量消耗CPU资源;
     
    互斥锁的使用前提:多条线程抢夺同一块资源;
     
    相关术语:线程同步;
    线程同步的含义:多条线程按顺序执行任务;
    互斥锁就是使用了线程同步技术;
     
    7.原子属性和非原子属性
     
    OC在定义属性时有nonatomic和atomic两种选择:
    atomic:原子属性,为setter方法加锁(默认就是atomic);
    nonatomic:非原子属性,不会为setter方法加锁;
     
    atomic加锁原理:
    1 @property (assign, atomic) int age;
    2 - (void)setAge:(int)age
    3 {
    4 @synchronized(self) {
    5     _age = age;
    6   }
    7 }
     
    nonatomic和atomic对比
    nonatomic:线程安全,需要消耗大量的资源;
    atomic:线程不安全,适合内存较小的移动设备;
     
    iOS的开发建议:
    所有属性都定义为nonatomic;
    尽量避免多线程抢夺同一块资源;
    尽量将加锁,资源抢夺的业务逻辑都交给服务器端处理,减少移动客户端的压力;
     
    8.线程间通信
     
    一个线程传递数据给另一个线程;
    一个线程执行完任务,转到另一个线程继续执行任务;
     
    线程之间常用的通信方法
    1 - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
    2 - (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;
  • 相关阅读:
    Remote desktop manager共享账号
    content is not supported outside 'script" or asp content' region
    How to pass values across the pages in ASP.net without using Session
    GitLab Flow
    C#如何获取系统downloads和documents路径
    sql server查询结果复制出来,没有换行(存进去的数据是换行的)
    Type Interceptors
    JsonNode、JsonObject常用方法
    java获取当前时间戳的方法
    Java中float/double取值范围与精度
  • 原文地址:https://www.cnblogs.com/zfan/p/3805036.html
Copyright © 2011-2022 走看看