NSThread
- 实现多线程的技术方案之一.
- 面向对象的开发思想.
- 每个对象表示一条线程.
创建线程三种方式
1.对象方法创建
实例化线程对象的同时指定线程执行的方法@selector(demo:).
需要手动开启线程.
- (void)threadDemo1
{
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(demo:) object:@"alloc"];
// 手动启动线程
[thread start];
}
2.类方法创建
分离出一个线程,并且自动开启线程执行@selector(demo:).
无法获取到线程对象
- (void)threadDemo2
{
[NSThread detachNewThreadSelector:@selector(demo:) toTarget:self withObject:@"detach"];
}
- 这两种方式的区别是:
后一种一调用就会立即创建一个线程来做事情;而前一种虽然你 alloc 了也 init 了,但是要直到我们手 动调用 start 启动线程时才会真正去创建线程。这种延迟实现思想在很多跟资源相关的地方都有用到。前一种方式我们还可以 在启动线程之前,对线程进行配置,比如设置 stack 大小,线程优先级。
还有一种间接的方式,更加方便,我们甚至不需要显式编写 NSThread 相关代码。那就是利用 NSObject 的类方法
3.NSObject(NSThreadPerformAdditions) 的分类创建
- 方便任何继承自NSObject的对象,都可以很容易的调用线程方法
- 无法获取到线程对象
- 自动开启线程执行@selector(demo:).
- (void)threadDemo3
{
[self performSelectorInBackground:@selector(demo:) withObject:@"perform"];
}
总结
- 以上三种创建线程的方式,各有不同.随意选择.
- 使用哪种方式需要根据具体的需求而定.比如 : 如果需要线程对象,就使用对象方法创建.