美文网首页
NSThread的基本使用

NSThread的基本使用

作者: lyonLiu | 来源:发表于2016-09-21 18:28 被阅读41次

使用NSThread创建线程的两种方式一个NSThread对象对应一条线程
第一种方式:使用alloc init 创建线程,必须手动启动线程
优点:可对线程进行更详细的设置,如下述设置线程名称和优先级

- (void)thread
{
    //创建线程
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(threadSelector) object:nil];
    //设置线程名称
    [thread setName:@"a"];
    //线程优先级  取值范围 0.1 ~ 1.0之间  默认优先级是0.5
    thread.threadPriority = 1;
    //启动线程
    [thread start];
    
    //创建线程
    NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(threadSelector) object:nil];
    [thread1 setName:@"b"];
    //启动线程
    [thread1 start];
}

- (void)threadSelector{
    NSLog(@"%@",[NSThread currentThread]);
}

特别说明:
以下述方式启动线程,线程方法是在内部 - (void)main;函数中调用
大家可继承NSThread,尝试在main函数中输出结果

NSThread *thread = [[NSThread alloc]init];
//启动线程
[thread start];

第二种方式:分离子线程,会自动启动线程
优点:简单快捷
缺点:无法对线程进行更详细的设置

- (void)thread{
    //创建线程
    [NSThread detachNewThreadSelector:@selector(threadSelector) toTarget:self withObject:nil];
}

- (void)threadSelector{
    NSLog(@"%@",[NSThread currentThread]);
}
@end

开启一条后台线程

- (void)thread3{
    
    [self performSelectorInBackground:@selector(threadSelector) withObject:nil];
}

相关文章

  • IOS多线程的方式

    pthread的基本使用(需要包含头文件) 需要#import 3 NSThread (1)NSThread的基本...

  • iOS多线程与网络(1)--基本概念

    1 基本概念 2 pthread 3 NSThread (1)NSThread的基本使用 (2)设置线程的属性 (...

  • 第一天

    第1天 1 基本概念 2 pthread 3 NSThread (1)NSThread的基本使用 (2)设置线程的...

  • 多线程学习总结

    第1天 1 基本概念 2 pthread 3 NSThread (1) NSThread的基本使用 (2)线程的状...

  • 网络多线程

    第1天 1 基本概念 2 pthread 3 NSThread (1)NSThread的基本使用 (2)设置线程的...

  • iOS—多线程的基本概念及实现方式

    第1天 1 基本概念 2 pthread 3 NSThread (1)NSThread的基本使用 (2)设置线程的...

  • iOS 多线程(三)NSThread的使用

    一、NSThread基本介绍   NSThread是OC中封装程度最小最轻量级的,使用更灵活,基本使用比较简单,但...

  • NSThread的基本使用

    使用NSThread创建线程的两种方式一个NSThread对象对应一条线程第一种方式:使用alloc init 创...

  • IOS多线程

    1.基本概念 2.pthread 3.NSThread (1)NSThread的基本使用 (2)设置线程的属性 (...

  • 爱上多线程 之 GCD

    2 pthread 3 NSThread (1)NSThread的基本使用 (2)设置线程的属性 (3)线程的状态...

网友评论

      本文标题:NSThread的基本使用

      本文链接:https://www.haomeiwen.com/subject/aphwettx.html