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;

                }

            }

        }

    }

  • 相关阅读:
    HashMap 链表插入方式 → 头插为何改成尾插 ?
    MySQL 日志之 binlog 格式 → 关于 MySQL 默认隔离级别的探讨
    Eclipse
    Delphi
    Delphi
    Delphi
    Delphi
    Delphi
    Delphi
    Delphi
  • 原文地址:https://www.cnblogs.com/tangranyang/p/4713672.html
Copyright © 2011-2022 走看看