NSThread是基于Objective-C的,相比pthread而言,它使用起来更简单和方便。下面我们就新建一个工程,来看一下NSThread的简单使用。
一、NSThread的基本使用
NSThread有三种开启子线程的方法,分别是- initWithTarget: selector: object:、- detachNewThreadSelector: toTarget: withObject:和- performSelectorInBackground: withObject:。下面就简单的演示一下这三种方法如何使用。
1、使用- initWithTarget: selector: object:创建子线程
- (void)viewDidLoad {
[super viewDidLoad];
// 创建子线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(test:) object:@"我是参数"];
// 给子线程命名
thread.name = @"我是子线程";
// 设置子线程的优先级
thread.threadPriority = 0.5; // 取值范围是(0.0 ~ 1.0), 默认为0.5
// 启动线程
[thread start];
}
- (void)test:(id)argument {
NSLog(@"%@, %@", [NSThread currentThread], argument);
}
通过- initWithTarget: selector: object:方法来创建的子线程,它默认是处于暂停状态的,必须拿到线程对象调用- start方法来开启。另外,selector:后面传入的方法是可以带参数的,而这个参数就是通过object:后面的参数进行传递。
再补充一点,关于线程的优先级,它的取值范围是从0.0 ~ 1.0,子线程创建完成以后,系统默认它的优先级是0.5。在同时创建有多个子线程的场合中,优先级高的子线程被系统执行的概率要高于优先级低的子线程。
2、使用- detachNewThreadSelector: toTarget: withObject:创建子线程
- (void)viewDidLoad {
[super viewDidLoad];
// 创建子线程
[NSThread detachNewThreadSelector:@selector(test:) toTarget:self withObject:@"我是参数"];
}
- (void)test:(id)argument {
NSLog(@"%@, %@", [NSThread currentThread], argument);
}
- detachNewThreadSelector: toTarget: withObject:的使用方法跟- initWithTarget: selector: object:方法差不多,只不过,通过这种方式创建出来的子线程,你无法拿到它,这样一来,你就没办法给它设置优先级了。
3、使用- performSelectorInBackground: withObject:创建子线程
- (void)viewDidLoad {
[super viewDidLoad];
// 创建子线程
[self performSelectorInBackground:@selector(test:) withObject:@"我是参数"]; // 开启一条后台线程
}
- (void)test:(id)argument {
NSLog(@"%@, %@", [NSThread currentThread], argument);
}
通过- performSelectorInBackground: withObject:创建的是一条隐式线程。它的使用方法跟- detachNewThreadSelector: toTar