美文网首页
3.线程安全

3.线程安全

作者: HFY_Code | 来源:发表于2016-08-19 14:29 被阅读0次
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;
            }
        }
    }
}

相关文章

  • 3.线程安全

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

  • 面试问题

    1.spring mvc 2.线程安全:主要是问线程安全,static修饰的一定线程安全吗? 3.线程池 4.团队...

  • 设计模式-单例模式

    1.懒汉式-线程不安全 2.懒汉式-线程安全 3.饿汉式-线程安全 4.饿汉式-静态代码块-线程安全 5.懒汉式-...

  • 创建型模式 --- 单例

    1.懒汉式,线程不安全 2.懒汉式,线程安全 3.饿汉式,线程安全 4.枚举,线程安全 5.双检锁/双重校验锁

  • Java单例的7种写法

    1. 懒汉式(线程不安全) 2. 懒汉式(线程安全) 优点:线程安全; 缺点:加了同步,效率低; 3. 饿汉式 特...

  • 深入JVM内核原理-4.JVM锁

    1.JVM锁概要 JVM锁概要.png 2.线程安全 JVM线程安全1.pngJVM线程安全2.png 3.对象头...

  • 《Java 并发编程实战》对象的组合

    目录 1.设计线程安全的类2.实例封闭3.线程安全性的委托4.在现有的线程安全类中添加功能 1.设计线程安全的类 ...

  • Kotlin 单例

    1.懒汉模式 java kotlin 2.懒加载(非线程安全) java kotlin 3.懒加载(线程安全) j...

  • iOS底层原理总结 - 多线程的锁

    目录:1.为什么要线程安全2.多线程安全隐患分析3.多线程安全隐患的解决方案4.锁的分类-13种锁4.1.1OSS...

  • 多线程3线程带来的安全风险

    线程带来的风险:1.线程安全问题2.活跃性问题3.性能问题

网友评论

      本文标题:3.线程安全

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