多线程 - 03.NSThread使用

1.NSThread基本使用

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
  // 1.创建子线程
    /*
     Target: 子线程需要调用谁的方法
     selector: 被子线程调用的方法
     object: 调用方法时, 给方法传递的参数
     */
    // 注意: 如果线程正在执行, 那么系统会自动强引用NSThread retained during the execution of the detached thread
    // 当线程中的任务执行完毕, 系统会自动释放线程, 对线程进行一次release操作 they are released when the thread finally exits.
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(demo:) object:@"ZJ"];
    // 1.1设置线程基本属性
    // 设置线程名称
    thread.name = @"线程2";
    // 设置优先级,注意优先级取值范围时0~1,数值越大,优先级越高,但是优先级越高不代表系统会先执行此线程,而是CPU调度该线程的可能性更大
    thread.threadPriority = 0.8;
    // 2.启动线程
    // 注意点: 如果通过alloc/init创建NSThread, 那么需要手动启动线程
    [thread start];

}

-(void)demo:(NSString *)str{
    NSLog(@"%@",str);// 输出结果:ZJ
    NSLog(@"%@", [NSThread currentThread]);
    // 输出结果:<NSThread: 0x7fab72d11f40>{number = 2, name = 线程2}q
    for (int i = 0; i < 100; i++) {
        NSLog(@"i = %i",i);
    }
}

2.NSThread的其他创建方式

    // 方式一:创建子线程
    /*
     优点:
     - 使用简便
     - 如果通过detach方法创建线程, 不需要手动调用start启动线程,系统会自动启动
     缺点:
     - 不可以进行其它设置
     - 通过detach方法创建子线程是没有返回值的
     应用场景:
     - 如果仅仅需要简单的开启一个子线程执行一些操作, 不需要对子线程进行其它设置, 那么推荐使用detach方法创建线程
     */
//    [NSThread detachNewThreadSelector:@selector(demo:) toTarget:self withObject:@"MrRight"];
    // 方式二:
    // 系统会自动在后台给我们开启一个子线程, 并且会自动启动该线程执行任务
    [self performSelector:@selector(demo:) withObject:@"MrRightZJ"];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值