#import "ViewController.h"
@interface ViewController ()
/**售票员A*/
@property(nonatomic ,strong) NSThread *thread01;
/**售票员B*/
@property(nonatomic ,strong) NSThread *thread02;
/**售票员C*/
@property(nonatomic ,strong) NSThread *thread03;
/** 总共有多少长票*/
@property (nonatomic ,assign) NSInteger totalCount;
@property(nonatomic ,strong) NSObject *obj;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.thread01 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread01.name = @"售票员A";
self.thread02 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread02.name = @"售票员B";
self.thread03 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread03.name = @"售票员C";
self.totalCount = 100;
self.obj = [[NSObject alloc]init];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self.thread01 start];
[self.thread02 start];
[self.thread03 start];
}
-(void)saleTicket
{
while (1) {
//锁对象:全局唯一的,而且只能会一把所
@synchronized(self) {
NSInteger count = self.totalCount;
if (count >0) {
self.totalCount = count - 1;
[NSThread sleepForTimeInterval:0.2];
NSLog(@"%@卖出了一张票,还剩下%zd张票",[NSThread currentThread].name,self.totalCount);
}else
{
NSLog(@"票已经卖完了...");
break;
}
}
}
}
@end