首页 > 学院 > 开发设计 > 正文

@synchronized 互斥锁

2019-11-06 09:56:44
字体:
来源:转载
供稿:网友

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

}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表