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

时间:2023-03-08 16:24:33

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

}

}

}

}