#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, assign) NSInteger ticket;
@property (nonatomic, strong) NSObject *obj;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.obj = [[NSObject alloc]init];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
self.ticket = 20;
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];
thread.name = @"售员01";
[thread start];
NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];
thread1.name = @"售员02";
[thread1 start];
}
- (void)saleTicket {
while (YES) {
[NSThread sleepForTimeInterval:1.f];
@synchronized(self) {
if (self.ticket > 0) {
self.ticket --;
NSLog(@"卖出一张票 %zd %@",self.ticket,[NSThread currentThread]);
continue;
}
NSLog(@"卖完了");
break;
}
}
}
@end