#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) {
//互斥鎖保證鎖內(nèi)代碼在同一時(shí)間只能有一條線程執(zhí)行 //互斥鎖 加鎖范圍盡量小 越大效率越大 //self參數(shù)為任意OC對(duì)象 加鎖對(duì)象必須是全局變量 局部變量無法鎖住 @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; } }}}