NSThread简介
NSThread是基于线程使用,轻量级的多线程编程方法(相对GCD和NSOperation),一个NSThread对象代表一个线程,需要手动管理线程的生命周期,处理线程同步等问题。
属性和方法
属性和方法 | 解释 |
---|---|
isExecuting | 线程是否在执行 |
isCancelled | 线程是否被取消 |
isFinished | 线程是否完成 |
isMainThread | 是否是主线程 |
threadPriority | 线程的优先级,取值范围0.0到1.0,默认优先级0.5,1.0表示最高优先级,优先级高,CPU调度的频率高 |
+(NSThread *)currentThread | 获取当前线程 |
+(void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument | 创建启动线程 |
+(BOOL)isMultiThreaded | 判断是否是多线程 |
+(void)sleepUntilDate:(NSDate *)date | 线程休眠到NSDate |
+(void)sleepForTimeInterval:(NSTimeInterval)time | 线程休眠NSTimeInterval |
-(void)start | 启动线程 |
+(void)exit | 结束/退出当前线程 |
+(double)threadPriority | 获取当前线程优先级 |
+(BOOL)setThreadPriority:(double)priority | 设置线程优先级 默认为0.5 取值范围为0.0 - 1.0,1.0优先级最高 |
+(BOOL)isMainThread NS_AVAILABLE(10_5, 2_0) | 判断当前线程是否是主线程 |
+(NSThread *)mainThread NS_AVAILABLE(10_5, 2_0) | 获取主线程 |
-(double)threadPriority NS_AVAILABLE(10_6, 4_0) | 获取指定线程的优先级 |
-(void)setThreadPriority:(double)p NS_AVAILABLE(10_6, 4_0) | 设置指定线程的优先级 |
-(void)setName:(NSString *)n NS_AVAILABLE(10_5, 2_0) | 设置线程的名字 |
-(NSString *)name NS_AVAILABLE(10_5, 2_0) | 获取线程的名字 |
-(BOOL)isMainThread NS_AVAILABLE(10_5, 2_0) | 判断指定的线程是否是 主线程 |
-(id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument NS_AVAILABLE(10_5, 2_0) | 创建线程 |
-(BOOL)isExecuting NS_AVAILABLE(10_5, 2_0) | 指定线程是否在执行 |
-(BOOL)isFinished NS_AVAILABLE(10_5, 2_0) | 线程是否完成 |
-(BOOL)isCancelled NS_AVAILABLE(10_5, 2_0) | 线程是否被取消 (是否给当前线程发过取消信号) |
-(void)cancel NS_AVAILABLE(10_5, 2_0) | 发送线程取消信号的 最终线程是否结束 由 线程本身决定 |
-(void)start NS_AVAILABLE(10_5, 2_0) | 启动线程 |
-(void)main NS_AVAILABLE(10_5, 2_0) | 线程主函数 在线程中执行的函数 都要在-main函数中调用,自定义线程中重写-main方法 |
使用方法
方式1
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(doSth) object:nil];
thread.name = @"thread1";
[thread start];
- (void)doSth{
NSLog(@"%@",[NSThread currentThread]);
}
打印结果
2019-11-15 13:24:33.655155+0800 iosTest[33058:1857339] <NSThread: 0x600003fbf9c0>{number = 3, name = thread1}
方式2
该方法会自动创建一个子线程,并在子线程中执行。
[NSThread detachNewThreadSelector:@selector(doSth) toTarget:self withObject:nil];
- (void)doSth{
NSLog(@"%@",[NSThread currentThread]);
}
打印结果
2019-11-15 13:26:54.993327+0800 iosTest[33108:1859499] <NSThread: 0x6000018152c0>{number = 3, name = (null)}
方式3
该方法会开启一条后台线程,并在后台线程中执行。
[self performSelectorInBackground:@selector(doSth) withObject:nil];
- (void)doSth{
NSLog(@"%@",[NSThread currentThread]);
}
方式4
在主线程上执行任务,即返回主线程。
[self performSelectorOnMainThread:@selector(doSth) withObject:nil waitUntilDone:NO];