zoukankan      html  css  js  c++  java
  • iOS 线程间共享资源添加排它锁

    #import "ViewController.h"


    @interface ViewController ()


    @property(nonatomic,strong)NSThread *thread1;

    @property(nonatomic,strong)NSThread *thread2;

    @property(nonatomic,strong)NSThread *thread3;


    //剩余票

    @property(nonatomic,assign)NSInteger leftTickets;





    @end


    @implementation ViewController


    - (void)viewDidLoad {

        [super viewDidLoad];

        self.leftTickets=100;//总票数

        

        // 初始化三个卖票窗口

        self.thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTickets:) object:@"1号窗口"];

        self.thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTickets:) object:@"2号窗口"];

        self.thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTickets:) object:@"3号窗口"];

        

    }


    -(void)touchesBegan:(NSSet *)touches withEvent:( UIEvent *)event

    {

        //开始买票

        [self.thread1 start];

        [self.thread2 start];

        [self.thread3 start];

        

        

    }



    -(void)saleTickets:(NSString*)str

    {

        while (1) {

            @synchronized(self) {

                [NSThread sleepForTimeInterval:0.5];

                if(self.leftTickets>0)

                {

                    self.leftTickets--;

                    NSLog(@"余票:%ld,买票的进程:%@",self.leftTickets,[NSThread currentThread]);

                }

                else

                {

                    return;

                }

            }

        }

    }

  • 相关阅读:
    Eclipse Mac OS 安装 Subversion插件subclipse 缺失JavaHL解决方案
    Eclipse Mac OS 安装 最新版 Subversion插件subclipse
    mac OS 安装 Homebrew软件包管理器
    Ribbon 框架简介及搭建
    Ribbon 框架简介及搭建
    TinyMCE下载及使用
    努力啊。
    逃离
    怎么学习
    烂代码
  • 原文地址:https://www.cnblogs.com/tangranyang/p/4713672.html
Copyright © 2011-2022 走看看