码迷,mamicode.com
首页 > 移动开发 > 详细

iOS 线程间共享资源添加排它锁

时间:2015-08-08 19:45:20      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

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

            }

        }

    }

}

iOS 线程间共享资源添加排它锁

标签:

原文地址:http://www.cnblogs.com/tangranyang/p/4713672.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!