iOS-进阶学习iOS学习笔记Ios自己面试总结

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

2016-06-12  本文已影响171人  一抹月光3053
创建和启动线程
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"];
线程的状态
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;
//进入阻塞状态
//注意:一旦线程停止(死亡)了,就不能再次开启任务
多线程的安全隐患
屏幕快照 2016-06-12 下午2.50.00.png 屏幕快照 2016-06-12 下午2.51.35.png 屏幕快照 2016-06-12 下午2.52.52.png
安全隐患解决 - 互斥锁
屏幕快照 2016-06-12 下午2.54.26.png
@synchronized(锁对象){//需要锁定的代码}
//注意锁定一份代码只用1把锁,用多把锁是无效的

-互斥锁代码示例:

#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
原子和非原子属性的选择
线程间通信
 - (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
上一篇下一篇

猜你喜欢

热点阅读