iOS多线程-NSThread

在IOS多线程中NSThread这种方式虽然简单易用,但是需要程序员管理,所以在实际开发中使用较少。这里只简单介绍。方便更好的理解GCD和NSOperation。

  • NSThread创建

    //1.创建方式
    NSThread *thread = [[NSThread alloc] initWithTarget:self   selector:@selector(demo:) object:@"Thread"];
    //启动线程
    [thread start];
    //2.创建方式
    [NSThread detachNewThreadSelector:@selector(demo:) toTarget:self withObject:@"Detach"];
    //3.创建方式
    [self performSelectorInBackground:@selector(demo:) withObject:@"background"];
    
  • 常用属性和方法

    //设置线程名字
    @property (nullable, copy) NSString *name
    //阻断
    + (void)sleepForTimeInterval:(NSTimeInterval)ti;
    //终止线程
    + (void)exit;
    //设置优先级
    + (BOOL)setThreadPriority:(double)p;
    
  • 线程间的通讯方法

    //主线程
    - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array;
    //主线程
    - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
    //子线程
    - (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait modes:(nullable NSArray<NSString *> *)array ;
    //子线程
    - (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait 
    //子线程
    - (void)performSelectorInBackground:(SEL)aSelector withObject:(nullable id)arg ;
    
  • 互斥锁
    互斥锁:保证锁内的代码,同一时间只有1个线程执行。
    互斥锁的范围:尽量要小,范围大,效率就会差。
    例子:

    self.tickets = 20;
    NSThread *t1 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTickets) object:nil];
      t1.name = @"售票员B";
      [t1 start];
    
    NSThread *t2 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTickets) object:nil];
      t2.name = @"售票员A";
      [t2 start];
    
    -(void)saleTickets
    {
        while (YES) {
          [NSThread sleepForTimeInterval:1.0];
          //这个地方添加互斥锁,保证买票的代码执行是在同一线程。
          @synchronized (self) {
              if (self.tickets > 0) {
                  self.tickets--;
                  NSLog(@"剩下%d张票 %@",self.tickets,[NSThread currentThread]);
              }else
              {
                  NSLog(@"卖完了");
                  break;
              }
          }    
      }    
    }
    
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容