多线程 ---- NSThread和线程安全

作者: 一抹月光3053 | 来源:发表于2016-06-12 15:20 被阅读171次
创建和启动线程
  • 一个NSThread对象就代表一条线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"jack"];
[thread start];
//线程一启动,就会在线程thread中执行self的run方法
  • 主线程相关方法
 + (NSThread *)mainThread//获得主线程
 + (BOOL)isMainThread//是否为主线程
 - (BOOL)isMainThread//是否为主线程
  • 其他方法
  • 获得当前线程
NSThread *current = [NSThread currentThread];
  • 线程的名字
  - (void)setName:(NSString *)name;
  - (NSString *)name;
其他创建线程方式
  • 创建线程后自动启动线程
[NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"rose"];
  • 隐式创建并启动线程
 [self performSelectorInBackground:@selector(run:) withObject:@"jack"];
  • 上述两种创建线程方式的优缺点
    p 优点:简单快捷
    p 缺点:无法对线程进行更详细的设置
线程的状态
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run:) object:@"jack"];
屏幕快照 2016-06-12 下午2.36.59.png
控制线程的状态
- (void)start;
//进入就绪状态 -> 运行状态。当线程任务执行完毕,自动进入死亡状态
  • 阻塞(暂停线程)
 + (void)sleepUntilDate:(NSDate *)date;
 + (void)sleepForTimeInterval:(NSTimeInterval)ti;
//进入阻塞状态
//注意:一旦线程停止(死亡)了,就不能再次开启任务
多线程的安全隐患
  • 资源共享
    p 一块资源可能会被多个线程共享,也就是多个线程可能会访问同一块资源。
    p 比如多个线程访问同一个对象、同一个变量、同一个文件

  • 当多个线程访问同一块资源时,很容易引发数据错乱和数据安全问题。

  • 安全隐患示例01 - 存钱取钱

屏幕快照 2016-06-12 下午2.50.00.png
  • 安全隐患示例02 - 卖票
屏幕快照 2016-06-12 下午2.51.35.png
  • 安全隐患分析
屏幕快照 2016-06-12 下午2.52.52.png
安全隐患解决 - 互斥锁
屏幕快照 2016-06-12 下午2.54.26.png
  • 互斥锁使用格式
@synchronized(锁对象){//需要锁定的代码}
//注意锁定一份代码只用1把锁,用多把锁是无效的
  • 互斥锁的优缺点
    1 优点:能有效防止因多线程抢夺资源造成的数据安全问题
    2 缺点:需要消耗大量的CPU资源

  • 互斥锁的使用前提:多条线程抢夺同一块资源

  • 相关专业术语:线程同步
    p 线程同步的意思是:多条线程在同一条线上执行(按顺序的执行任务)
    p 互斥锁,就是使用了线程同步技术。

-互斥锁代码示例:

#import "ViewController.h"

@interface ViewController ()
/** 售票员01 */
@property (nonatomic, strong) NSThread *thread01;
/** 售票员02 */
@property (nonatomic, strong) NSThread *thread02;
/** 售票员03 */
@property (nonatomic, strong) NSThread *thread03;

/** 票的总数 */
@property (nonatomic, assign) NSInteger ticketCount;

/** 锁对象 */
//@property (nonatomic, strong) NSObject *locker;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.locker = [[NSObject alloc] init];
    
    self.ticketCount = 100;
    
    self.thread01 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
    self.thread01.name = @"售票员01";
    
    self.thread02 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
    self.thread02.name = @"售票员02";
    
    self.thread03 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
    self.thread03.name = @"售票员03";
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.thread01 start];
    [self.thread02 start];
    [self.thread03 start];
}

- (void)saleTicket
{
    while (1) {
        @synchronized(self) {
            // 先取出总数
            NSInteger count = self.ticketCount;
            if (count > 0) {
                self.ticketCount = count - 1;
                NSLog(@"%@卖了一张票,还剩下%zd张", [NSThread currentThread].name, self.ticketCount);
            } else {
                NSLog(@"票已经卖完了");
                break;
            }
        }
    }
}

@end
原子和非原子属性的选择
  • nonatomic和atomic对比
    p atomic :线程安全,需要消耗大量的资源
    p nonatomic :非线程安全,是和内存小的移动设备

  • iOS开发的建议

  • 1.所有属性都声明为nonatomic

  • 2.尽量避免多线程抢夺同一块资源

  • 3.尽量将加锁、资源抢夺的业务逻辑交给服务器端处理,减小移动客户端的压力。

线程间通信
  • 什么叫做线程间通信
    p 在一个进程中,线程往往不是孤立存在的,多个线程之间需要经常通信。

  • 线程间通信的提现
    p 一个线程传递数据给另一个线程
    p 在一个线程中执行完特定任务后,转到另一个线程继续执行任务

  • 线程间通信常用方法

 - (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

相关文章

网友评论

  • 9ee6c54cbdf7:图文并茂 形象生动 写的一首好文章

本文标题:多线程 ---- NSThread和线程安全

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