那什么时候需要加锁呢,就是当多条线程同时操作一个变量时,就需要加锁了。
上代码
声明变量
@interface ViewController ()
@property (strong, nonatomic)NSThread *thread1;
@property (strong, nonatomic)NSThread *thread2;
@property (strong, nonatomic)NSThread *thread3;
@property (assign, nonatomic)int leftTickets;
@end
实现代码
- (void)viewDidLoad {
[super viewDidLoad];
self.thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTickets) object:nil];
self.thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTickets) object:nil];
self.thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTickets) object:nil];
self.thread1.name = @"thread1";
self.thread2.name = @"thread2";
self.thread3.name = @"thread3";
// 总票数
self.leftTickets = 10;
}
// 点击屏幕开启线程
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self.thread1 start];
[self.thread2 start];
[self.thread3 start];
}
- (void)sellTickets {
while (1) {
@synchronized (self) {
if (self.leftTickets > 0) {
[NSThread sleepForTimeInterval:0.2];
int count = self.leftTickets;
self.leftTickets = count - 1;
NSLog(@"剩余的票数%d",self.leftTickets);
NSLog(@"当前线程=%@", [NSThread currentThread]);
}else {
NSLog(@"票卖完了");
NSLog(@"退出线程%@",[NSThread currentThread]);
[NSThread exit];
}
}
}
}
打印日志
2016-11-04 11:52:25.117 TTTTTTTTTT[6753:74162] 剩余的票数9
2016-11-04 11:52:25.117 TTTTTTTTTT[6753:74162] 当前线程=<NSThread: x608000073880>{number = 3, name = thread1}
2016-11-04 11:52:25.393 TTTTTTTTTT[6753:74163] 剩余的票数8
2016-11-04 11:52:25.393 TTTTTTTTTT[6753:74163] 当前线程=<NSThread: x608000074540>{number = 4, name = thread2}
2016-11-04 11:52:25.661 TTTTTTTTTT[6753:74164] 剩余的票数7
2016-11-04 11:52:25.661 TTTTTTTTTT[6753:74164] 当前线程=<NSThread: x608000074580>{number = 5, name = thread3}
2016-11-04 11:52:25.932 TTTTTTTTTT[6753:74162] 剩余的票数6
2016-11-04 11:52:25.933 TTTTTTTTTT[6753:74162] 当前线程=<NSThread: x608000073880>{number = 3, name = thread1}
2016-11-04 11:52:26.164 TTTTTTTTTT[6753:74163] 剩余的票数5
2016-11-04 11:52:26.165 TTTTTTTTTT[6753:74163] 当前线程=<NSThread: x608000074540>{number = 4, name = thread2}
2016-11-04 11:52:26.438 TTTTTTTTTT[6753:74164] 剩余的票数4
2016-11-04 11:52:26.439 TTTTTTTTTT[6753:74164] 当前线程=<NSThread: x608000074580>{number = 5, name = thread3}
2016-11-04 11:52:26.704 TTTTTTTTTT[6753:74162] 剩余的票数3
2016-11-04 11:52:26.705 TTTTTTTTTT[6753:74162] 当前线程=<NSThread: x608000073880>{number = 3, name = thread1}










