iOS 多线程之NSThread

前言

NSThread是苹果官方提供面向对象操作线程的技术,简单方便,可以直接操作线程对象,不过需要自己控制线程的生命周期.在平时使用很少,最常用到就是[NSThread currentThread]获取当前线程.

1 NSThread简述

Apple官方文档

  • 一个NSThread对象就代表一条线程
  • NSThread会在执行完任务函数是被自动收回

2 NSThread创建

  • 动态创建
NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(threadFunction1:) object:@"初始化: thread"];

NSThread *thread2 = [[NSThread alloc] initWithBlock:^{
    NSLog(@"初始化: thread2");
}];
NSThread *thread3 = [[NSThread alloc] init];

thread1, thread2, thread3需要调用start开启

  • 静态创建
// 由于静态方法没有返回值,如果需要获取新创建的thread,需要在selector中调用获取当前线程的方法
[NSThread detachNewThreadSelector:@selector(threadFunction2:) toTarget:self withObject:@"静态创建"];

3 NSThread方法

  • 开始和取消
// 线程开始
[thread1 start];
// 线程取消
[thread cancel];
  • 线程停止
    线程停止 停止方法会立即终止除主线程以外所有线程(无论是否在执行任务)并退出,需要在掌控所有线程状态的情况下调用此方法,否则可能会导致内存问题
    一旦停止则不能重启
[NSThread exit];
  • 线程方法
// 是否是主线程
[NSThread isMainThread];
// 设置为主线程
[NSThread mainThread];
// 获取当前线程
[NSThread currentThread];
// 设置线程优先级
[NSThread currentThread].qualityOfService = NSQualityOfServiceBackground;

// 线程暂停
[NSThread sleepForTimeInterval:1.0];
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];

4 线程间通信方法

  • 指定当前线程执行
[self performSelector:@selector(threadFunction)];
[self performSelector:@selector(threadFunction) withObject:nil];
[self performSelector:@selector(threadFunction) withObject:nil afterDelay:2.0];
  • 其他线程中指定主线程执行
[self performSelectorOnMainThread:@selector(threadFunction) withObject:nil waitUntilDone:YES];

  • 在主线程中指定其他线程执行操作
//这里指定为某个线程
[self performSelector:@selector(threadFunction) onThread:newThread
withObject:nil waitUntilDone:YES];

//这里指定为后台线程
[self performSelectorInBackground:@selector(threadFunction) withObject:nil];

  • 线程同步

线程和其他线程可能会共享一些资源,当多个线程同时读写同一份共享资源的时候,可能会引起冲突.线程同步是指是指在一定的时间内只允许某一个线程访问某个资源

iOS实现线程加锁有NSLock@synchronized两种方式

优点:能有效防止因多线程抢夺资源造成的数据安全问题
缺点:需要消耗大量的CPU资源

5 NSThread的使用:模拟售票

情景:某电影院门票发售,在窗口A窗口B均开设窗口进行销售,以下是代码实现

{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(threadExit) name:NSThreadWillExitNotification object:nil];
    // 票数20
    self.ticketsCount = 20;

    NSThread *windowA = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
    windowA.name = @"窗口A";
    [windowA start];

    NSThread *windowB = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
    windowB.name = @"窗口B";
    [windowB start];
}

// 售票
- (void)saleTicket {
    //线程启动后,执行saleTicket,执行完毕后就会退出,为了模拟持续售票的过程,

    while (1) {
        // 添加互斥锁
        if (self.ticketsCount > 0) {
            self.ticketsCount--;

            NSLog(@"%@, %ld", [NSThread currentThread].name, (long)self.ticketsCount);
            [NSThread sleepForTimeInterval:0.2];
        } else {
            break;
        }
    }
}

- (void)threadExit {
    NSLog(@"线程退出");
}

执行结果:

窗口A, 12
窗口A, 11
窗口B, 10
窗口B, 8
窗口A, 8
窗口B, 7
窗口A, 6
窗口B, 5
窗口A, 4
窗口B, 3
窗口A, 2
窗口B, 0
窗口A, 1

售票过程中,多个线程访问同一资源,导致数量错乱,售票过程中我们给票加上互斥锁.
同一时间内,只有一个线程能对票的数量进行操作,当操作完成之后,其他线程才能继续对票的数量进行操作.

@synchronized(self)添加互斥锁
- (void)saleTicket {
    //线程启动后,执行saleTicket,执行完毕后就会退出,为了模拟持续售票的过程,

    while (1) {
        // 添加互斥锁
        @synchronized(self) {
            if (self.ticketsCount > 0) {
                self.ticketsCount--;

                NSLog(@"%@, %ld", [NSThread currentThread].name, (long)self.ticketsCount);
                [NSThread sleepForTimeInterval:0.2];
            } else {
                break;
            }
        }
    }
    //执行完线程就退出了
}

打印结果:

窗口B, 6
窗口B, 5
窗口A, 4
窗口A, 2
窗口B, 3
窗口B, 1
窗口A, 1
窗口B, 0
设置线程一直运行,自定义取消
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(threadExit) name:NSThreadWillExitNotification object:nil];
    // 票数20
    self.ticketsCount = 20;

    NSThread *windowA = [[NSThread alloc] initWithTarget:self selector:@selector(threadWindowA) object:nil];
    windowA.name = @"窗口A";
    [windowA start];

    NSThread *windowB = [[NSThread alloc] initWithTarget:self selector:@selector(threadWindowB) object:nil];
    windowB.name = @"窗口B";
    [windowB start];

    [self performSelector:@selector(saleTicket) onThread:windowA withObject:nil waitUntilDone:NO];
    [self performSelector:@selector(saleTicket) onThread:windowB withObject:nil waitUntilDone:NO];
}

- (void)threadWindowA {
    NSRunLoop *runLoop1 = [NSRunLoop currentRunLoop];
    //一直运行
    [runLoop1 runUntilDate:[NSDate date]];
}

- (void)threadWindowB {
    NSRunLoop *runLoop2 = [NSRunLoop currentRunLoop];
    //自定义运行时间
    [runLoop2 runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:12.0]];
}

// 售票
- (void)saleTicket {
    //线程启动后,执行saleTicket,执行完毕后就会退出,为了模拟持续售票的过程,

    while (1) {
        // 添加互斥锁
        if (self.ticketsCount > 0) {
            self.ticketsCount--;

            NSLog(@"%@, %ld", [NSThread currentThread].name, (long)self.ticketsCount);
            [NSThread sleepForTimeInterval:0.2];
        } else {
            //如果已卖完,关闭售票窗口
            if ([NSThread currentThread].isCancelled) {
                break;
            } else {
                NSLog(@"售卖完毕");
                //自定义线程停止时机
                
                //给当前线程标记为取消状态
                [[NSThread currentThread] cancel];
                //停止当前线程的runLoop
                CFRunLoopStop(CFRunLoopGetCurrent());
            }
        }
    }
}

- (void)threadExit {
    NSLog(@"线程退出:%@", [NSThread currentThread].name);
}

完整代码见GitHub->多线程


如有不足之处,欢迎予以指正, 如果感觉写的不错,记得给个赞呦!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. 线程的概念 首先简单叙述一下这两个概念,我们在电脑上单独运行的每个程序就是一个独立的进程,通常进程之间是相互...
    大成小栈阅读 3,262评论 0 0
  • iOS多线程开发基础概念 进程 VS 线程 进程:程序的一次执行,是正在执行的程序的实例,它是Unix的一个基本概...
    qingmarch阅读 2,944评论 0 1
  • 前面总结了多线程基本概念和iOS多线程PThread的使用,下面接着总结iOS多线程的另外一种实现方案NSThre...
    YANGXIXIYear阅读 1,501评论 0 0
  • 0. 前言 NSThread 是 iOS 多线程当中最基础最轻量的多线程技术,但是需要自行管理线程的生命周期和同步...
    24小时营业阅读 5,030评论 0 0
  • 什么是线程?什么是进程?线程和进程什么关系?这不是我们这一章关心的重点,我在这里假设大家都知道线程是cpu调度的最...
    随风流逝阅读 2,920评论 0 1