• 线程3--线程安全


    线程安全指的是当多个线程可能会访问同一块资源

    比如多个线程访问同一个对象、同一个变量、同一个文件

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

     

    - (void)viewDidLoad {
        //默认有20张票
        self.leftTicketsCount=20;
        //开启多个线程,模拟售票员售票
        
        self.thread1=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
        
        self.thread1.name=@"售票员A";
        
        self.thread2=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
        
        self.thread2.name=@"售票员B";
        
        self.thread3=[[NSThread alloc]initWithTarget:self selector:@selector(sellTickets) object:nil];
        
        self.thread3.name=@"售票员C";
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    }
    -(void)sellTickets
    {
        while (1) {
            @synchronized(self){//只能加一把锁,下面为同步代码块;
                //1.先检查票数
                int count=self.leftTicketsCount;
                if (count>0) {
                    //暂停一段时间
                    [NSThread sleepForTimeInterval:0.002];
                    //2.票数-1
                    self.leftTicketsCount= count-1;
                    //获取当前线程
                    NSThread *current=[NSThread currentThread];
                    NSLog(@"%@--卖了一张票,还剩余%d张票",current,self.leftTicketsCount);
                }else
                {
                    //退出线程
                    [NSThread exit];
                }
            }
        }
    }
    
    
    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        
        //开启线程
        [self.thread1 start];
        [self.thread2 start];
        [self.thread3 start];
    }
  • 相关阅读:
    Kafka开启JMX监控
    不用再上官网,自己部署一套ElementUI官方最新文档
    Idea没安装几款好用的插件,怎么风骚的写代码???
    springboot2.x基础教程:动手制作一个starter包
    springboot2.x基础教程:自动装配原理与条件注解
    Java Jar源码反编译工具那家强
    Jmeter 乱码解决方法
    robot frame基础知识--变量
    HTML基础--标签
    yaml模块
  • 原文地址:https://www.cnblogs.com/sunjianfei/p/5725010.html
Copyright © 2020-2023  润新知