使用NSThread创建线程的两种方式一个NSThread对象对应一条线程
第一种方式:使用alloc init 创建线程,必须手动启动线程
优点:可对线程进行更详细的设置,如下述设置线程名称和优先级
- (void)thread
{
//创建线程
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(threadSelector) object:nil];
//设置线程名称
[thread setName:@"a"];
//线程优先级 取值范围 0.1 ~ 1.0之间 默认优先级是0.5
thread.threadPriority = 1;
//启动线程
[thread start];
//创建线程
NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(threadSelector) object:nil];
[thread1 setName:@"b"];
//启动线程
[thread1 start];
}
- (void)threadSelector{
NSLog(@"%@",[NSThread currentThread]);
}
特别说明:
以下述方式启动线程,线程方法是在内部 - (void)main;
函数中调用
大家可继承NSThread,尝试在main函数中输出结果
NSThread *thread = [[NSThread alloc]init];
//启动线程
[thread start];
第二种方式:分离子线程,会自动启动线程
优点:简单快捷
缺点:无法对线程进行更详细的设置
- (void)thread{
//创建线程
[NSThread detachNewThreadSelector:@selector(threadSelector) toTarget:self withObject:nil];
}
- (void)threadSelector{
NSLog(@"%@",[NSThread currentThread]);
}
@end
开启一条后台线程
- (void)thread3{
[self performSelectorInBackground:@selector(threadSelector) withObject:nil];
}
网友评论