iOS多线程技术1 - NSThread的一般用法

NSThread 简介

NSThread 是苹果官方提供的面向对象类线程操作技术,简单方便,可以直接操作线程对象,不过需要自己控制线程的生命周期,在平时使用较少。

开启线程

使用 NSThread 开启线程有类方法和实例方法两种,类方法会直接执行任务,实例方法需要在实例初始化后调用 start 方法才能开始执行任务。

类方法创建线程

使用类方法创建线程后会自动开始任务,不需要手动开启。类方法创建线程有如下两种方式:

// block 方式
+ (void)detachNewThreadWithBlock:(void (^)(void))block;
     
// SEL 方式
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullable id)argument;

block 方式:

[NSThread detachNewThreadWithBlock:^{
   
    NSLog(@"class method -- task in block, current thread is %@", [NSThread currentThread]);
}];

// 执行后打印:class method -- task in block, current thread is <NSThread: 0x6000022f2300>{number = 4, name = (null)}

SEL 方式:

[NSThread detachNewThreadSelector:@selector(classMethodTest) toTarget:self withObject:nil];

- (void)classMethodTest {
   
    NSLog(@"class method -- task in SEL, current thread is %@", [NSThread currentThread]);
}

// 执行后打印:class method -- task in SEL, current thread is <NSThread: 0x6000022e76c0>{number = 3, name = (null)}

实例方法创建线程

实例方法创建线程也是分为 block 和 SEL 两种方式:

// block 方式
- (instancetype)initWithBlock:(void (^)(void))block;
     
// SEL 方式
- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullable id)argument;

block 方式:

// 1. 创建线程
NSThread *oneThread = [[NSThread alloc] initWithBlock:^{
   
    
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值