一个NSThread实例代表一条线程(了解,较少使用)
初始化
- 动态,需要start开启
-init
-initWithTarget:selector:object:
-initWithBlock
- 静态,直接开启
+detachNewThreadSelector:toTarget:withObject:
+detachNewThreadWithBlock:
- 隐式创建
-performSelectorInBackground:selector:object:
暂停取消和销毁
+ sleepUntilDate:
Blocks the current thread until the time specified.
+ sleepForTimeInterval:
Sleeps the thread for a given time interval.
+ exit
Terminates the current thread.
- cancel
Changes the cancelled state of the receiver to indicate that it should exit.
判断线程状态
Thread’s Execution State
executing
A Boolean value that indicates whether the receiver is executing.
finished
A Boolean value that indicates whether the receiver has finished execution.
cancelled
A Boolean value that indicates whether the receiver is cancelled.
线程间通信
在主线程执行
performSelectorInBackground
在指定线程上执行
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait NS_AVAILABLE(10_5, 2_0);
在当前线程上执行
-performSelector
在后台线程上执行
-performSelectorInBackground
优缺点
- 优点:直观地控制线程对象
- 缺点:需要自己管理线程的生命周期,线程同步。线程同步对数据的加锁会有一定的系统开销
网友评论