多线程之NSThread的使用

来源:互联网 发布:百丽运动旗舰店 知乎 编辑:程序博客网 时间:2024/05/29 17:34

创建线程三种方式

课程目标

  • 掌握创建线程的三种方式

准备新线程执行的方法

- (void)demo:(id)obj{    NSLog(@"传入参数 => %@",obj);    NSLog(@"hello %@",[NSThread currentThread]);}

对象方法创建

  • 实例化线程对象的同时指定线程执行的方法@selector(demo:).
  • 需要手动开启线程.
- (void)threadDemo1{    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(demo:) object:@"alloc"];    // 手动启动线程    [thread start];}

类方法创建

  • 分离出一个线程,并且自动开启线程执行@selector(demo:).
  • 无法获取到线程对象
- (void)threadDemo2{    [NSThread detachNewThreadSelector:@selector(demo:) toTarget:self withObject:@"detach"];}

NSObject(NSThreadPerformAdditions) 的分类创建

  • 方便任何继承自NSObject的对象,都可以很容易的调用线程方法
  • 无法获取到线程对象
  • 自动开启线程执行@selector(demo:).
- (void)threadDemo3{    [self performSelectorInBackground:@selector(demo:) withObject:@"perform"];}

总结

  • 以上三种创建线程的方式,各有不同.随意选择.
  • 使用哪种方式需要根据具体的需求而定.比如 : 如果需要线程对象,就使用对象方法创建.