iOS 多线程(二)NSThread

iOS 使用NSThread来代表线程,创建新线程也就是创建一个NSThread对象。

1 创建和启动线程

iOS10之前提供了两种方法开启线程。

- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullable id)argument NS_AVAILABLE(10_5, 2_0);
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullable id)argument;
第一种方法是实例方法,返回一个NSThread对象,必须调用start方法来启动线程。

第二种方法是类方法,不会返回NSThread对象,直接创建并启动线程。

iOS10增加了两种创建启动线程的方法

- (instancetype)initWithBlock:(void (^)(void))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
+ (void)detachNewThreadWithBlock:(void (^)(void))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
这两个方法与上述类似,也是一个实例方法,一个类方法。只是执行方法体不一样了。
具体使用如下:

#import "ZPYViewController.h"

@interface ZPYViewController ()

@end

@implementation ZPYViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    [self makeThread1beforeIOS10];
    [self makeThread2beforeIOS10];
    [self makeThread1FromIOS10];
    [self makeThread2FromIOS10];
}
-(void)run{
    for(int i=0;i<10;i++){
        NSLog(@"%@,----i=%d",[NSThread currentThread],i);
        NSLog(@"isMainThread=%d",[NSThread isMainThread]);
    }
}

//iOS 10 之前NSThread两种方法创建线程。如下:
-(void) makeThread1beforeIOS10{
    //第一种创建方式 实例方法 最多可以传一个参数
    NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    [thread1 setName:@"fisrt blood"];
    //启动线程
    [thread1 start];
    BOOL isMain = [NSThread isMainThread];
    NSLog(@"isMain=%d,thread1=%d",isMain,[thread1 isMainThread]);
}
//第二种创建方式 类方法。 最多可以传一个参数
-(void) makeThread2beforeIOS10{
    //类方法,不会返回NSThread对象,直接启动线程
    [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
}
//iOS 10又添加了两个方法创建线程。
// 需要iOS 10 才可以运行下面两个方法。否则会出错。
//第三种创建方式 实例方法
-(void) makeThread1FromIOS10{
    NSThread *thread3 = [[NSThread a
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值