3.线程安全

4.线程安全与互斥锁.png

######## 互斥锁就像茅房的门上的锁,就一个坑,不能都进去吧!😄😄,一个一个来!

#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;

@end

@implementation ViewController

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

推荐阅读更多精彩内容

  • 在上篇中,我们已经讨论过如何去实现一个 Map 了,并且也讨论了诸多优化点。在下篇中,我们将继续讨论如何实现一个线...
    一缕殇流化隐半边冰霜阅读 12,283评论 5 41
  • 当我从大学离开后,一直按照自己在毕业时给自己设计的路线前进,后退,前进,后退。把自己固定在可以计算的宽度里,维持着...
    酒笑生阅读 1,690评论 0 1
  • 好多天了,忙忙碌碌奔跑不停,居然连更新简书的时间都没有,心理素质极差的我,因为找工作的压力睡不着觉了,常常睡不好,...
    曦宝阅读 715评论 0 1
  • 7.27日客感悟:彼得原理 ———————————— 不要将晋升当作是一种激励手段,都说不想当将军的士兵不是好士兵...
    张琪77阅读 1,267评论 0 0
  • 昨晚我是11点半倒头便睡着了,半夜醒来发现儿子还在客厅玩手机游戏,这时已经凌晨1点半,我有点生气,唠叨了几句,儿子...
    瑾言珅行阅读 1,397评论 3 2