iOS-多线程之NSThread

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];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值