1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| #import "ViewController.h"
@interface ViewController () @property(nonatomic,strong) NSThread *thread1; @property(nonatomic,strong) NSThread *thread2; @property(nonatomic,strong) NSThread *thread3; @property(nonatomic,assign) int leftTicketCount;//剩余票数
@end
@implementation ViewController
- (void)viewDidLoad { [super viewDidLoad]; self.leftTicketCount=100; self.thread1=[[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil]; self.thread1.name=@"1号窗口"; self.thread2=[[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil]; self.thread2.name=@"2号窗口"; self.thread3=[[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil]; self.thread3.name=@"3号窗口"; self.locker=[[NSObject alloc]init]; } -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self.thread1 start]; [self.thread2 start]; [self.thread3 start]; } //卖票 -(void)saleTicket { while (1) { int count=self.leftTicketCount; if (count>0) { [NSThread sleepForTimeInterval:0.1]; self.leftTicketCount=count-1; NSLog(@"%@卖了一张票,剩余%d张票",[NSThread currentThread].name,count); }else{ return;//退出死循环 } } } @end
|