OC_NSThread

184 阅读1分钟

NSThread概述

NSThread 是一个使用起来比 pthread 更加面向对象,简单易用,可以直接操作线程对象的类。由程序员自己管理线程的生命周期, NSThread 在开发过程中会偶尔使用,常被用来获取当前线程编号等操作。

NSThread 的常用属性

线程状态相关属性

属性 类型 解释
executing BOOL 只读,返回该线程是否正在执行
finished BOOL 只读,返回该线程是否已经执行完毕
cancelled BOOL 只读,返回该线程是否已经取消执行

线程对象相关属性

属性 类型 解释
isMainThread BOOL 只读,当前线程是否是主线程
mainThread NSThread 只读,返回主线程对象
currentThread NSThread 只读,返回当前线程对象
name NSString 设置线程名
threadPriority double 设置线程优先级

NSThread 的常用方法

  • 创建并启动线程

+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullable id)argument;

  • 线程对象实例化方法

- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullable id)argument;

  • 隐式创建并启动线程

- (void)performSelectorInBackground:(SEL)aSelector withObject:(nullable id)arg

  • 开始该线程

- (void)start;

  • 取消该线程

- (void)cancel

  • 线程阻塞到一个时间点

+ (void)sleepUntilDate:(NSDate *)date;

  • 线程阻塞一段时间

+ (void)sleepForTimeInterval:(NSTimeInterval)ti;

  • 结束线程

+ (void)exit;

NSThread线程通信