#import "ResourceSharing.h"
@interface ResourceSharing ()
@property(assign,nonatomic) int tickets;
@property(strong,nonatomic) NSString *str;
@end
@implementation ResourceSharing
- (void)viewDidLoad {
[super viewDidLoad];
self.str = [[NSString alloc]init];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
self.tickets = 20;
NSThread *t1= [[NSThread alloc]initWithTarget:self selector:@selector(saleTickets) object:nil];
t1.name = @"AAAAA";
[t1 start];
NSThread *t2= [[NSThread alloc]initWithTarget:self selector:@selector(saleTickets) object:nil];
t2.name = @"BBBBB";
[t2 start];
}
-(void)saleTickets{
while (YES) {
//互斥锁保证锁内代码在同一时间只能有一条线程执行
//互斥锁 加锁范围尽量小 越大效率越大
//self参数为任意OC对象 加锁对象必须是全局变量 局部变量无法锁住
@synchronized (self.str) {
[NSThread sleepForTimeInterval:0.2];
if (self.tickets > 0) {
self.tickets--;
NSLog(@"剩余%d%@",self.tickets,[NSThread currentThread]);
} else {
NSLog(@"卖完了%d%@",self.tickets,[NSThread currentThread]);
break;
}
}
}
}