#import "ViewController.h"
@interface ViewController ()
//火车票
@property (nonatomic,assign) int tickets;
@property (nonatomic,strong) NSObject *obj;
//nonatomic 非原子属性:多个线程可同时读取、赋值
//atomic 原子属性:多个线程下,只有一线程可对变量赋值,多个线程可同时读取
//自旋锁
@property (atomic,strong) NSObject *obj2;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.tickets = 5;
self.obj = [[NSObject alloc] init];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(sellTicket) object:nil];
[thread1 start];
NSThread *thread2 = [[NSThread alloc]initWithTarget:self selector:@selector(sellTicket) object:nil];
[thread2 start];
}
- (void)sellTicket{
while (YES) {
//模拟网络延时
[NSThread sleepForTimeInterval:1];
//锁是任意对象,默认锁是开着的
//同步锁(互斥锁) 自选锁不能代替同步锁
@synchronized(self) {
if (self.tickets > 0) {
_tickets -= 1;
NSLog(@"剩余 %d 张票",_tickets);
continue;
}
NSLog(@"票卖完了");
break;
}
}
}