iOS线程其一NSThread

之前的文章,我简单分别介绍了四种线程。现在介绍其中一种的NSThread怎么用

//大多数方法默认都在主线程

这是一个触摸模拟器就会响应的方法

第一种《《《《《《《《《《《《

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

      //创建线程

      //object参数

  NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"jack"];

      //启动线程

  [thread start];

      //线程一启动,就会在线程thread中执行selfrun方法

   thread.name = @"my - thread";

    //是否在主线程

   [thread isMainThread];


}

- (void)run:(NSString *)param{

    NSLog(@"-------run------%@-----%@",param,[NSThread currentThread]);

}

打印结果


//这个线程做完就会死掉

接下来,我们来证明线程是否会死掉

第一步.创建一个新的类.h.m 继承NSThread 


在新建的XMGThread文件中写

#import "XMGThread.h"

@implementation XMGThread

- (void)dealloc{

    NSLog(@"dealloc");

}

@end



第二步.在ViewController里引入头文件 

#import "XMGThread.h"

把NSThread 全部改成 XMGThread 运行一下。打印出来的结果


说明线程走完会死掉

第二种《《《《《《《《《《《《

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [self createThread2];

}

- (void)createThread2{

    //在主线程直接分出一条线程 创建新的线程

    [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"rose"];

}

第三种《《《《《《《《《《《《

//大多数方法默认都在主线程

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    [self createThread3];

   }

- (void)createThread3{

    //开一个后台线程  子线程

    [self performSelectorInBackground:@selector(run:) withObject:@"jack"];

    

}


//第二,第三种 不用alloc init一个线程

//优点简单快捷

//缺点 无法对线程更详细设置













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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值