@synchronized(对象)中的这个"对象"是什么,锁定它是为了什么
在 sellTicket 中锁定了 self , 如果在 ticket 中没有用@synchronized(self),就会在sellTicket中线程运行的情况下,运行ticket中的线程,
如果用了@synchronized(self) 所有线程就会一个一个运行
//============== 代码部分 =================
@property (nonatomic, assign) NSInteger ticket;
-
(void)viewDidLoad {
[super viewDidLoad];_ticket = 50;
[NSThread detachNewThreadSelector:@selector(sellTicket) toTarget:self withObject:nil];
[NSThread detachNewThreadSelector:@selector(sellTicket) toTarget:self withObject:nil];[NSThread detachNewThreadSelector:@selector(ticket123) toTarget:self withObject:nil];
[NSThread detachNewThreadSelector:@selector(sellTicket) toTarget:self withObject:nil];
[NSThread detachNewThreadSelector:@selector(sellTicket) toTarget:self withObject:nil];
}
-
(void)sellTicket{
while (_ticket > 0) {
[NSThread sleepForTimeInterval:3]; @synchronized (self){ if (_ticket > 0) { NSLog(@"123"); [NSThread sleepForTimeInterval:3]; self.ticket--; NSLog(@"%@ %ld ", [NSThread currentThread], _ticket); } }
}
} -
(void)ticket123 {
// @synchronized (self) {
for (int i = 0; i < 10; i++) {[NSThread sleepForTimeInterval:1]; self.ticket--; NSLog(@"ticker %ld", _ticket); }
}
}