多线程之NSThread的简单使用

  NSThread是基于Objective-C的,相比pthread而言,它使用起来更简单和方便。下面我们就新建一个工程,来看一下NSThread的简单使用。

一、NSThread的基本使用

  
  NSThread有三种开启子线程的方法,分别是- initWithTarget: selector: object:、- detachNewThreadSelector: toTarget: withObject:和- performSelectorInBackground: withObject:。下面就简单的演示一下这三种方法如何使用。

  1、使用- initWithTarget: selector: object:创建子线程

- (void)viewDidLoad {
    [super viewDidLoad];

    // 创建子线程
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(test:) object:@"我是参数"];

    // 给子线程命名
    thread.name = @"我是子线程";

    // 设置子线程的优先级
    thread.threadPriority = 0.5;  // 取值范围是(0.0 ~ 1.0), 默认为0.5

    // 启动线程
    [thread start];
}

- (void)test:(id)argument {

    NSLog(@"%@, %@", [NSThread currentThread], argument);
}

  通过- initWithTarget: selector: object:方法来创建的子线程,它默认是处于暂停状态的,必须拿到线程对象调用- start方法来开启。另外,selector:后面传入的方法是可以带参数的,而这个参数就是通过object:后面的参数进行传递。

  再补充一点,关于线程的优先级,它的取值范围是从0.0 ~ 1.0,子线程创建完成以后,系统默认它的优先级是0.5。在同时创建有多个子线程的场合中,优先级高的子线程被系统执行的概率要高于优先级低的子线程。

  2、使用- detachNewThreadSelector: toTarget: withObject:创建子线程

- (void)viewDidLoad {
    [super viewDidLoad];

    // 创建子线程
    [NSThread detachNewThreadSelector:@selector(test:) toTarget:self withObject:@"我是参数"];
}

- (void)test:(id)argument {

    NSLog(@"%@, %@", [NSThread currentThread], argument);
}

  - detachNewThreadSelector: toTarget: withObject:的使用方法跟- initWithTarget: selector: object:方法差不多,只不过,通过这种方式创建出来的子线程,你无法拿到它,这样一来,你就没办法给它设置优先级了。

  3、使用- performSelectorInBackground: withObject:创建子线程

- (void)viewDidLoad {
    [super viewDidLoad];

    // 创建子线程
    [self performSelectorInBackground:@selector(test:) withObject:@"我是参数"];  // 开启一条后台线程
}

- (void)test:(id)argument {

    NSLog(@"%@, %@", [NSThread currentThread], argument);
}

  通过- performSelectorInBackground: withObject:创建的是一条隐式线程。它的使用方法跟- detachNewThreadSelector: toTar

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值