4.線程安全與互斥鎖.png
######## 互斥鎖就像茅房的門上的鎖,就一個(gè)坑掌栅,不能都進(jìn)去吧秩仆!????,一個(gè)一個(gè)來(lái)猾封!
#import "ViewController.h"
@interface ViewController ()
/** 售票員01 */
@property (nonatomic, strong) NSThread *thread01;
/** 售票員02 */
@property (nonatomic, strong) NSThread *thread02;
/** 售票員03 */
@property (nonatomic, strong) NSThread *thread03;
/** 票的總數(shù) */
@property (nonatomic, assign) NSInteger ticketCount;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.ticketCount = 100;
self.thread01 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread01.name = @"售票員01";
self.thread02 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread02.name = @"售票員02";
self.thread03 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread03.name = @"售票員03";
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.thread01 start];
[self.thread02 start];
[self.thread03 start];
}
- (void)saleTicket
{
while (1)
{
//開鎖進(jìn)茅房蹲坑
@synchronized(self)
{
// 先取出總數(shù)
NSInteger count = self.ticketCount;
if (count > 0)
{
self.ticketCount = count - 1;
NSLog(@"%@賣了一張票澄耍,還剩下%zd張", [NSThread currentThread].name, self.ticketCount);
} else
{
NSLog(@"票已經(jīng)賣完了");
break;
}
}
}
}