1.NSThread的创建方式
a.动态方法创建
/**
* 创建NSThread线程
*
* @param target selector消息发送的对象
* @param sel selector消息(即执行方法)
* @param arg 传给selector的唯一参数,也可以是nil
*
* @return NSThread线程对象
*/
- (nullable instancetype)initWithTarget:(id)target selector:(SEL)sel object:(nullable id)arg;
eg:
//创建线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadRun) object:nil];
//让线程开始执行
[thread start];
b.静态方法创建
/**
* 创建线程
*
* @param selector selector消息(即执行方法)
* @param target selector消息发送的对象
* @param argument 传给selector的唯一参数,也可以是nil
*/
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullable id)argument;
eg:
[NSThread detachNewThreadSelector:@selector(threadRun) toTarget:self withObject:nil];
注意:使用静态方法创建NSThread时,创建的线程时默认开始的,如果使用动态方法一定要手动开始。
c.利用隐式创建线程的方法
[self performSelectorInBackground:@selector(reloadMyData) withObject:nil];
2.NSThread常用方法
a.获取当前线程
NSThread *currentThread = [NSThread currentThread];
b.获取主线程
NSThread *mainThread = [NSThread mainThread];
c.暂停当前线程
[NSThread sleepForTimeInterval:0.5];
3.NSThread中各个线程之间的通讯
a.在指定线程上进行操作
[self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:YES];
b.在主线程上进行操作
[self performSelectorOnMainThread:@selector(refreshData) withObject:nil waitUntilDone:YES];
c.在当前线程上进行操作
[self performSelector:@selector(run) withObject:nil];
4.NSThread优缺点
优点:
NSThread相比于GCD、NSOperation较轻量级,更能够直接地控制线程对象
缺点:
需要自己管理线程的生命周期以及线程同步,会照成一定的系统开销(线程同步对数据加锁)